How to Use Promise.all in JavaScript
Running several promises at the same time with Promise.all.
There are times when you need data from a few different places before you can
render a page, like a user, their posts and their settings. If you await each
request one after the other, each one waits for the last to finish. When the
requests don't depend on each other, you can run them all at once with
Promise.all.
Promise.all() takes an array of promises and returns a single promise that
resolves with an array of all their results.
Requests One at a Time
Here's the slow way:
const user = await fetchUser()const posts = await fetchPosts()const settings = await fetchSettings()
If each request takes one second, this takes three seconds.
Requests at the Same Time
With Promise.all all three start right away:
const [user, posts, settings] = await Promise.all([fetchUser(),fetchPosts(),fetchSettings(),])
Now it takes about as long as the slowest request, around one second. The
results come back in the same order as the promises you passed in, no matter
which one finished first, so destructuring them is safe. If you're new to
await, check out
How to Use async and await in JavaScript.
Using Promise.all with map
Promise.all really shines when you have a list. Use
map to turn each item into a
promise:
const ids = [1, 2, 3]const users = await Promise.all(ids.map(async (id) => {const res = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`)return res.json()}))console.log(users.map((user) => user.name))// ["Leanne Graham", "Ervin Howell", "Clementine Bauch"]
When One Promise Fails
Promise.all fails fast. If any promise rejects, the whole thing rejects with
that error, and you don't get any of the other results:
try {await Promise.all([fetchUser(), fetchBrokenThing()])} catch (error) {console.error(error) // the error from fetchBrokenThing}
That's usually what you want when you need every result to continue.
Promise.allSettled
If you'd rather get every result, even when some fail, use Promise.allSettled.
It waits for all of the promises and tells you how each one went:
const results = await Promise.allSettled([fetchUser(), fetchBrokenThing()])// [// { status: "fulfilled", value: { name: "Jim" } },// { status: "rejected", reason: Error }// ]const successful = results.filter((result) => result.status === "fulfilled").map((result) => result.value)
Promise.allSettled is newer, but it works in Chrome 76+, Firefox 71+ and
Safari 13+. Use Promise.all when you need everything, and Promise.allSettled
when partial results are good enough.
Have some feedback on this post? .