Why does async/await not work inside forEach?

← JavaScript answers

forEach does not wait for the promises its callback returns, so the code after it runs before the work finishes. Use for...of or Promise.all(items.map(...)).

An async callback returns a promise, but forEach throws that promise away. The loop finishes immediately, and any error inside the callback becomes an unhandled rejection.

// Sequential: one request at a time
for (const id of ids) {
  await save(id);
}
 
// Parallel: all requests at once, wait for every one
await Promise.all(ids.map((id) => save(id)));
 
// Parallel, but keep going when some fail
const results = await Promise.allSettled(ids.map((id) => save(id)));

Choose for...of when order matters or when you must limit load on a server, and Promise.all when the calls are independent.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required