Promise.allSettled polyfill

Let us see how to write a polyfill for Promise.allSettled.

Promise.allSettled takes an array of promises as input and returns an array with the result of all the promises whether they are rejected or resolved.

According to MDN –

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

Reading the problem statement we can break it down into sub-problems and tackle them individually.

  • Map the array of promises to return an object with status and value/error depending upon the promised settlement.
  • Pass this map to the Promise.all to run them at once and return the result.
const allSettled = (promises) => {
  // map the promises to return custom response.
  const mappedPromises = promises.map(
    p => Promise.resolve(p)
    .then(
      val => ({ status: 'fulfilled', value: val }),
      err => ({ status: 'rejected', reason: err })
    )
  );

  // run all the promises once with .all 
  return Promise.all(mappedPromises);
}

Test Case

Input:
const a = new Promise((resolve) => setTimeout(() => { resolve(3) },200));
const b = new Promise((resolve,reject) => reject(9));
const c = new Promise((resolve) => resolve(5));

allSettled([a, b, c]).then((val)=> {console.log(val)});

Output:
[
  {
    "status": "fulfilled",
    "value": 3
  },
  {
    "status": "rejected",
    "reason": 9
  },
  {
    "status": "fulfilled",
    "value": 5
  }
]