Looping Through Async Methods in JavaScript
Running async functions in a loop with for...of and Promise.all.
There are times when you need to run an async function for every item in an
array, like fetching data for a list of users. Reaching for forEach feels
natural, but it won't wait for your promises to finish.
TL;DR Use for...of with await to run async calls one at a time, and
Promise.all with map to run them all at once.
For the examples below we'll use a fake getUser function that takes one
second to resolve:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms))async function getUser(id) {await wait(1000)return { id, name: `User ${id}` }}const ids = [1, 2, 3]
Why forEach Doesn't Wait
Here's what usually gets written first:
async function logUsers() {ids.forEach(async (id) => {const user = await getUser(id)console.log(user.name)})console.log("Done")}logUsers()// Done// User 1// User 2// User 3
"Done" logs before any of the users. forEach calls your callback for each
item and ignores whatever it returns. An async callback returns a promise, so
forEach starts all three calls and throws the promises away. There's nothing
for logUsers to wait on, and you can't await a forEach.
Running in Sequence with for...of
A for...of loop works with await, so each call finishes before the next one
starts:
async function logUsers() {for (const id of ids) {const user = await getUser(id)console.log(user.name)}console.log("Done")}logUsers()// User 1// User 2// User 3// Done
This takes about three seconds since each call waits for the one before it. Use this when the order matters, when each call depends on the previous one, or when you don't want to hit an API with a lot of requests at once.
Running in Parallel with Promise.all
If the calls don't depend on each other, you can start them all at the same
time. map returns an array of promises and Promise.all waits for all of
them:
async function logUsers() {const users = await Promise.all(ids.map((id) => getUser(id)))users.forEach((user) => console.log(user.name))console.log("Done")}logUsers()// User 1// User 2// User 3// Done
This takes about one second total instead of three. The results come back in the same order as the original array, no matter which promise finishes first.
Click Run to compare all three loops. Each getUser call here takes between
0.35 and 0.65 seconds, so you can see what each loop waits for.
forEach
- getUser(1): idle
- getUser(2): idle
- getUser(3): idle
Promise.all
- getUser(1): idle
- getUser(2): idle
- getUser(3): idle
for...of
- getUser(1): idle
- getUser(2): idle
- getUser(3): idle
If any of the promises reject, Promise.all rejects right away with that
error. Wrap it in a try...catch to
handle it:
async function logUsers() {try {const users = await Promise.all(ids.map((id) => getUser(id)))users.forEach((user) => console.log(user.name))} catch (error) {console.error(error.message)}}
Promise.allSettled
Sometimes you want every result, even if some of them fail.
Promise.allSettled waits for all of the promises to either resolve or
reject, and never rejects itself:
async function logUsers() {const results = await Promise.allSettled(ids.map((id) => getUser(id)))results.forEach((result) => {if (result.status === "fulfilled") {console.log(result.value.name)} else {console.error(result.reason)}})}
Each result is an object with a status of "fulfilled" or "rejected",
along with either a value or a reason. This is handy for things like
sending a batch of emails where one failure shouldn't stop the rest.
A Note on for await...of
There's also a for await...of loop. It's meant for async iterables, like
reading a Node.js stream in chunks or paging through an API:
async function logChunks(stream) {for await (const chunk of stream) {console.log(chunk)}}
You can use it on an array of promises too, but Promise.all is usually the
better fit there since it handles rejections more predictably.
To sum it up, skip forEach for async work. Use for...of when you need one
at a time and Promise.all when you want them all at once.
Have some feedback on this post? .