New promise resolve reject

A fundamental concept in JavaScript!

A Promise is a result object that is used to handle asynchronous operations. It has three states:

  1. Pending: Initial state, where the promise is waiting for its operation to complete.
  2. Fulfilled: The operation has completed successfully, and the promise has a value.
  3. Rejected: The operation has failed, and the promise has an error.

When a promise is created, it can be resolved or rejected. Here's what happens:

Resolve:

Example:

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Hello, world!"); // Resolve the promise with a value
  }, 2000);
});

promise.then((value) => {
  console.log(value); // Output: "Hello, world!"
});

Reject:

Example:

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject(new Error("Something went wrong")); // Reject the promise with an error
  }, 2000);
});

promise.catch((error) => {
  console.error(error); // Output: Error: Something went wrong
});

Chaining promises:

You can chain multiple promises together using the then() method. Each then() method returns a new promise that is resolved or rejected based on the outcome of the previous promise.

Example:

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Hello, world!"); // Resolve the promise with a value
  }, 2000);
});

promise.then((value) => {
  console.log(value); // Output: "Hello, world!"
  return value.toUpperCase(); // Return a new promise that resolves with the uppercase value
}).then((uppercaseValue) => {
  console.log(uppercaseValue); // Output: "HELLO, WORLD!"
});

In this example, the first then() method resolves the promise with the value "Hello, world!". The second then() method is called with the resolved value, and it returns a new promise that resolves with the uppercase value "HELLO, WORLD!".