ES6

Promise.allSettled() Polyfill

polyfill promise allSettled

polyfill promise allSettled

The Promise.allSettled() method returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise.

Now let’s try to implement the same behaviors as stated in the definition above.

1st step: is to create a method with an array of promises as parameters.

Promise.allSettled = function (promises) {}

2nd Step: We will use array.map() to map our promises. We will map each promise to return an object with properties:

  • status: It defines the status of the promise which is fulfilled when the promise is resolved and rejected when promise gets rejected.
  • value: This key holds the response of a fulfilled promise. This key is not present for rejected promises.
  • reason: This key holds the reason by which promise got rejected. This key is only present for rejected promises and not for fulfilled promises.
.then((value) => {
    return {
      status: 'fulfilled',
      value,
    };
  })
  .catch((reason) => {
    return {
      status: 'rejected',
      reason,
    };
  });

3rd step: As the definition says, it should return a single promise, so instead of creating a new promise we are going to make use of Promise.all() which itself will return the required promise.

return Promise.all(mappedPromises);

So our final polyfill looks like this now:

Promise.allSettled = function (promises) {
  let mappedPromises = promises.map((p) => {
    return p
      .then((value) => {
        return {
          status: 'fulfilled',
          value,
        };
      })
      .catch((reason) => {
        return {
          status: 'rejected',
          reason,
        };
      });
  });
  return Promise.all(mappedPromises);
};

Below is the live code for the polyfill of Promise.allSettled()

Let me know your thoughts

%d bloggers like this: