Wait for all promises to resolve in JavaScript
By Flavio
Published · Updated
Tagged: JavaScript
Learn how to start multiple promises at once and wait for all of them to resolve using await Promise.all(), instead of awaiting each one after another.
Sometimes we need to wait for a promise to resolve, and we also need to wait for another promise to resolve.
Something like this:
const values = await store.getAll()
const keys = await store.getAllKeys()
This works but it’s not ideal. First we’re waiting for the first call to be resolved, then we start the second.
I want to start both first, then I want to wait until both finished. Not a millisecond more.
The solution is to wrap all in a await Promise.all() call, like this:
const data = await Promise.all([store.getAll(), store.getAllKeys()])
Once this is resolved, we can access the first call value using data[0] and the second call return value with data[1].
Use destructuring to name the results
data[0] and data[1] are hard to read. I prefer array destructuring:
const [values, keys] = await Promise.all([
store.getAll(),
store.getAllKeys(),
])
The results always come back in the same order as the array you passed in, no matter which promise finished first.
How much faster is it?
Here’s a small test with a fake task that takes 500ms:
const wait = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms))
let start = Date.now()
const a = await wait(500, 'a')
const b = await wait(500, 'b')
console.log(Date.now() - start) // ~1000
start = Date.now()
const [c, d] = await Promise.all([wait(500, 'c'), wait(500, 'd')])
console.log(Date.now() - start) // ~500
One after the other takes the sum of all the times. With Promise.all() it takes as long as the slowest one.
This only helps when the calls don’t depend on each other. If the second call needs the result of the first one, you have to await them in order.
Wait for an array of promises
The most common case is running the same async function for every item of an array. Use map() to get an array of promises, then pass it to Promise.all():
const ids = [1, 2, 3]
const users = await Promise.all(ids.map((id) => fetchUser(id)))
Don’t use forEach() for this. It doesn’t wait for anything:
const users = []
ids.forEach(async (id) => {
users.push(await fetchUser(id))
})
console.log(users.length) // 0
forEach() calls your async function 3 times and moves on immediately, so the code after it runs before any user is loaded. I wrote more about this in how to use async/await with map.
What happens if one promise fails
Promise.all() rejects as soon as one of the promises rejects. You catch it with try/catch:
try {
const [user, posts] = await Promise.all([fetchUser(1), fetchPosts(1)])
} catch (error) {
console.error(error)
}
Two things to know:
- You get the error of the first promise that failed, and you lose the values of the ones that succeeded.
- The other promises are not cancelled. They keep running in the background, their result is just ignored. If they do something like writing to a database, that still happens.
If you want every result, even when some fail, use Promise.allSettled(). It never rejects, and gives you an object with the outcome of each promise:
const results = await Promise.allSettled([fetchUser(1), fetchPosts(1)])
// [
// { status: 'fulfilled', value: ... },
// { status: 'rejected', reason: Error }
// ]
for (const result of results) {
if (result.status === 'fulfilled') {
console.log(result.value)
} else {
console.error(result.reason)
}
}
I compared all 4 combinators in detail in Promise.all vs allSettled vs race vs any.
Don’t start promises and then await them one by one
You might think this is the same as Promise.all():
const p1 = fetchUser(1)
const p2 = fetchPosts(1)
const user = await p1
const posts = await p2
Both requests start at the same time, so it’s fast. But there’s a bug.
If p2 rejects while you’re still awaiting p1, nothing is handling that rejection yet. You get an unhandled promise rejection, and in Node.js that crashes the process, even if the code is wrapped in try/catch.
Promise.all() attaches a handler to every promise right away, so you don’t have this problem. Use it.
Edge cases
You can pass values that are not promises. They’re returned as they are:
await Promise.all([1, Promise.resolve(2), 'x']) // [1, 2, 'x']
An empty array resolves right away with an empty array:
await Promise.all([]) // []
Promise.all() only accepts an array (or another iterable), not an object. If you have an object of promises, convert it to entries and back:
const tasks = {
user: fetchUser(1),
posts: fetchPosts(1),
}
const entries = await Promise.all(
Object.entries(tasks).map(async ([key, promise]) => [key, await promise])
)
const { user, posts } = Object.fromEntries(entries)
Too many promises at once
Promise.all() doesn’t limit how many things run in parallel. If you map over 5,000 items and each one does a fetch(), you start 5,000 requests at the same time. The API you call might rate limit you, or you can run out of connections or memory.
In this case, split the array in batches and process one batch at a time:
const results = []
const batchSize = 10
for (let i = 0; i < items.length; i += batchSize) {
const batch = items.slice(i, i + batchSize)
const batchResults = await Promise.all(batch.map(processItem))
results.push(...batchResults)
}
See Promise.all, Promise.allSettled, Promise.race, and Promise.any for how it compares with the other combinators.
Want me to talk about your product? You can sponsor this site.
Related posts about js: