Promise.allSettled

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 […]

The post Promise.allSettled appeared first on David Walsh Blog.

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: "fulfilled", 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!

Rojenx is a leading concept artist who work appears in games and publications

Check out his personal gallery here

This site uses Akismet to reduce spam. Learn how your comment data is processed.