Why async forEach never waits
An async callback inside forEach runs, but nothing waits for it. Use for...of to run calls in order or Promise.all to run them together.
You wrote a loop that fetches a user for every id, pushed each result into an array, and the array is empty on the next line. The loop ran. Nothing waited for it.
const ids = [1, 2, 3]
const fetchUser = async (id) => ({ id })
const users = []
ids.forEach(async (id) => {
users.push(await fetchUser(id))
})
console.log(users.length) // 0The callback is marked async, so each call returns a promise. forEach throws that promise away. MDN’s forEach reference describes the same behavior.
forEach returns undefined, so await ids.forEach(...) still leaves the callback promises unobserved. Use the same ids and fetchUser in the next two examples.
Run them one after another
When each call depends on the previous one, or you want to go easy on an API, use for...of. It is a plain loop, so await inside it pauses the loop.
const users = []
for (const id of ids) {
users.push(await fetchUser(id))
}
console.log(users.length) // 3Three ids, three requests, one at a time, in order.
Run them all at once
When the calls are independent, start them together and wait once. map returns the promises; Promise.all fulfills once they all succeed, with results in input order.
const users = await Promise.all(ids.map((id) => fetchUser(id)))
console.log(users.length) // 3Same three results, in about the time of the slowest request instead of the sum of all three.
Which one
I reach for Promise.all first. Most loops over ids are independent, and the parallel version is one line.
I switch to for...of when the calls themselves need to happen in order or each needs the previous result. I also use it when firing every request at once would hit a rate limit.
If one request fails, Promise.all rejects with that error and the rest keep running in the background. For a list where some failures are fine, Promise.allSettled gives you every outcome instead.