How to Use Promise.allSettled in JavaScript
Running several promises at once and keeping every result, even failures.
When you run a few promises at once with
Promise.all, a single failure rejects
the whole thing. There are times when you'd rather keep the results that worked,
like a dashboard where one broken widget shouldn't blank out the whole page.
That's what Promise.allSettled is for.
Promise.allSettled() waits for every promise to finish, whether it resolves
or rejects, and tells you how each one went.
Basic Usage
Pass it an array of promises, just like Promise.all:
const results = await Promise.allSettled([Promise.resolve({ name: "Jim" }),Promise.resolve(["notification 1", "notification 2"]),Promise.reject(new Error("Weather service is down")),])console.log(results)// [// { status: "fulfilled", value: { name: "Jim" } },// { status: "fulfilled", value: ["notification 1", "notification 2"] },// { status: "rejected", reason: Error: Weather service is down }// ]
Each result is an object with a status. Fulfilled results have a value, and
rejected ones have a reason. The promise returned by Promise.allSettled
never rejects, so you don't need a catch around it. If await is new to you,
check out How to Use async and await.
Working with the Results
Split the results into what worked and what didn't:
const values = results.filter((result) => result.status === "fulfilled").map((result) => result.value)const errors = results.filter((result) => result.status === "rejected").map((result) => result.reason)
A Practical Example
Here's a dashboard that loads three widgets and shows an error only for the ones that fail:
const getJSON = async (url) => {const res = await fetch(url)if (!res.ok) throw new Error(`${url} returned ${res.status}`)return res.json()}const widgets = ["weather", "news", "stocks"]const results = await Promise.allSettled(widgets.map((name) => getJSON(`/api/widgets/${name}`)))results.forEach((result, index) => {const name = widgets[index]if (result.status === "fulfilled") {renderWidget(name, result.value)} else {renderError(name, result.reason.message)}})
The results come back in the same order as the promises, so index matches each
result to its widget.
Note: fetch only rejects on network errors, not on a 404 or 500. The
getJSON helper throws when res.ok is false so those count as rejected too.
Browser Support
Promise.allSettled is part of ES2020 and works in Chrome 76+, Firefox 71+,
Safari 13+ and Node 12.9+.
Use Promise.all when you need every result to continue, and
Promise.allSettled when you can work with whatever came back.
Have some feedback on this post? .