QRG: await vs Promise.all: Awaiting Arrays of Promises
๐ง Quick Reference: Awaiting Arrays of Promisesโ
โ Problemโ
You called an async function that returns an array of promises and expected this to work:
const result = await myAsyncBatchFunction(); // โ Doesn't work as expected
But result
is still an array of unresolved Promise
objects.
โ Fixโ
Use Promise.all(...)
to await the entire array:
const result = await Promise.all(myAsyncBatchFunction()); // โ
Now resolved
๐ Why?โ
await
unwraps one Promise- An array of promises is not a promise itself
Promise.all([...])
returns a single promise that resolves to an array of resolved values
๐งช Exampleโ
async function fetchAll() {
return [fetchUser(), fetchPosts()];
}
const result = await fetchAll(); // โ result is [Promise, Promise]
const resolved = await Promise.all(fetchAll()); // โ
resolved is [user, posts]
๐ก Rule of Thumbโ
If you're awaiting something that returns multiple things, and they're async, wrap it in
Promise.all()
โ even if it's from anasync
function.