DEV Community

Parthipan M
Parthipan M

Posted on

Promise in JS

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

To learn about the way promises work and how you can use them, we advise you to read Using promises first.

A Promise is in one of these states:

  • pending: initial state, neither fulfilled nor rejected.

  • fulfilled: meaning that the operation was completed successfully.

  • rejected: meaning that the operation failed.

A promise is said to be settled if it is either fulfilled or rejected, but not pending.


For Example:

new Promise((resolveOuter) => {
  resolveOuter(
    new Promise((resolveInner) => {
      setTimeout(resolveInner, 1000);
    }),
  );
});
Enter fullscreen mode Exit fullscreen mode

Promise itself has no first-class protocol for cancellation, but you may be able to directly cancel the underlying asynchronous operation, typically using

Chained Promises

The promise methods then(), catch(), and finally() are used to associate further action with a promise that becomes settled.

  • The then() method takes up to two arguments; the first argument is a callback function for the fulfilled case of the promise, and the second argument is a callback function for the rejected case.

  • The catch() and finally() methods call then() internally and make error handling less verbose.

  • For example, a catch() is really just a then() without passing the fulfillment handler. As these methods return promises, they can be chained.

For example:

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("foo");
  }, 300);
});

myPromise
  .then(handleFulfilledA, handleRejectedA)
  .then(handleFulfilledB, handleRejectedB)
  .then(handleFulfilledC, handleRejectedC);
Enter fullscreen mode Exit fullscreen mode

Promise concurrency

The Promise class offers four main static methods to facilitate async task

  • Promise.all()
    Fulfills when all of the promises fulfill; rejects when any of the promises rejects.

  • Promise.allSettled()
    Fulfills when all promises settle.

  • Promise.any()
    Fulfills when any of the promises fulfills; rejects when all of the promises reject.

  • Promise.race()
    Settles when any of the promises settles. In other words, fulfills when any of the promises fulfills; rejects when any of the promises rejects.

Constructor

Promise()

Creates a new Promise object. The constructor is primarily used to wrap functions that do not already support promises.

Static properties

Promise[Symbol.species]

Returns the constructor used to construct return values from promise methods.

Top comments (0)