Promise.allSettled

By  on  

The Promise object has many useful functions like all, resolve, reject, and race -- stuff we use all the time. One function that many don't know about is Promise.allSettled, a function that fires when all promises in an array are settled, regardless of whether any of the promises are resolved or rejected.

Promise.all is great but then isn't called if a project is rejected:

Promise.all([
  Promise.resolve(1),
  Promise.resolve(true),
  Promise.reject("Boooooo"),
])
.then(_ => console.log("Then!"))
.catch(e => console.log("catch!"));

// Catch!

There are always going to be cases where you'd like to run the then function regardless of individual results -- think hiding a spinner image at the end of multiple fetch requests; that's where Promise.allSettled comes in:

Promise.allSettled([
  Promise.resolve(1),
  Promise.resolve(true),
  Promise.reject("Boooooo"),
])
.then(promiseResults => console.log("Then! ", promiseResults))
.catch(e => console.log("catch!"));

/*
Then!
[
  { status: "fulfilled", value: 1 },
  { status: "fulfilled", value: true },
  { status: "rejected", reason: "Boooooo" }
]
*/

Promise.allSettled is awesome -- certainly much better than an old shim floating around years ago. Between all, allSettled, and race, as well as the ability to cancel fetch requests, we've almost got every aspect of Promises covered!

Recent Features

  • By
    Responsive Images: The Ultimate Guide

    Chances are that any Web designers using our Ghostlab browser testing app, which allows seamless testing across all devices simultaneously, will have worked with responsive design in some shape or form. And as today's websites and devices become ever more varied, a plethora of responsive images...

  • By
    CSS @supports

    Feature detection via JavaScript is a client side best practice and for all the right reasons, but unfortunately that same functionality hasn't been available within CSS.  What we end up doing is repeating the same properties multiple times with each browser prefix.  Yuck.  Another thing we...

Incredible Demos

Discussion

  1. I think the rejected results in the last code block should be:

     status: 'rejected', reason: 'Boooooo' }
  2. My only problem with this approach is that the .catch block never gets called with Promise.allSettled()

    • Werner

      Yes, that is import! Thank you Michel! Please correct that David.

  3. Terry

    So with allSettled is the .catch handler deprecated? When is it hit? Same with the onRejected param to then?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!