Polyfill for Promise.allSettled

Time for a new method to jump in for promises

Yash Sharma
2 min readSep 13, 2020

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

Right now Promise.all is in the proposal state. It is in stage 4 presets.

Personally I felt this was much needed and I had a lot of use cases where I could use something like this.

Status and reason is something which is introduced new here.

  • status: It is fulfilled when the promise is resolved and rejected when the promise gets rejected.
  • value: This represents the response of a fulfilled promise. It’s not present for rejected promises.
  • reason: This tells you the reason why your promise got rejected.
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);
};

The only difference this creates is, it allows you to not worry about what might fail or succeed and will give you the result irrespective of how many promises fail.
The problem with Promise.all was it will fail even if one promise is rejected (not really a problem, more like depends on your use case) and because of that, you won’t be able to rely on it if in your case you still want to go ahead with the rest of the responses or probably take care of the errors.

For more information do give this a read https://github.com/tc39/proposal-promise-allSettled

Thanks for reading. I hope you found this useful

Cheers!

--

--

Yash Sharma
Yash Sharma

Responses (1)