BitlystBitlyst
PostsSeriesTopicsAbout

Bitlyst

Short, diagram-first posts on JavaScript, React & Next.js. Follow via RSS or the newsletter.

© 2026 Mohsen Fallahnejad

PostsSeriesTopicsLinksAboutSync devicesRSSllms.txtGitHubX
Posts/javascript
AI-generated illustration. The loop has already left. The work it started is still in the air, and nobody is waiting for it.
Beginner4 min read

Part 3 of Common Mistakes

forEach and async/await: Why Your Loop Doesn't Wait

forEach with async/await doesn't wait. It starts every callback and returns undefined, so your code moves on early and errors skip your try/catch. Use for...of or Promise.all.

Mohsen Fallahnejad

Mohsen Fallahnejad

Nov 23, 2026Discuss

forEach with async/await looks like it waits. It doesn't. This passes code review all the time:

js
const results = [];

ids.forEach(async (id) => {
  results.push(await fetchUser(id));
});

console.log(results); // []

Each fetchUser takes 100 ms. The log runs at 0 ms and prints an empty array. About 150 ms later the array holds all three users, but by then nobody is reading it.

The mental model#

forEach starts every callback and walks away.

An async function returns a promise as soon as it hits its first await. forEach calls your callback, gets that promise back, throws it away and calls the next one. When all calls have started, forEach returns undefined. There is nothing to await, so await ids.forEach(...) doesn't help.

How it works#

The await inside the callback is real. It pauses that callback. It doesn't pause the loop, and it doesn't pause the function around the loop.

So three things happen:

  1. The code after the loop runs too early. It sees empty or half-filled data.
  2. The work runs in parallel, not in order. You may have expected one at a time.
  3. Errors escape. A try/catch around the forEach catches nothing. The rejection shows up later as an unhandledRejection, which crashes a Node process by default.
js
try {
  ids.forEach(async () => {
    throw new Error("boom");
  });
} catch {
  // never runs
}

Three lanes of blocks: launched with no one at the finish, in single file, and side by side through a gold gateThree lanes of blocks: launched with no one at the finish, in single file, and side by side through a gold gate Pick the lane on purpose: forEach launches and forgets, for...of goes one at a time, Promise.all goes together and waits at the gate.

The two fixes#

One at a time, in order: for...of.

js
for (const id of ids) {
  results.push(await fetchUser(id));
}

This one waits for real. Three 100 ms calls took 303 ms. Use it when order matters, when each step depends on the last, or when you must not hammer an API.

All at once, and wait for all: Promise.all + map.

js
const results = await Promise.all(ids.map((id) => fetchUser(id)));

map keeps the promises that forEach threw away. Promise.all waits for them and keeps the input order. The same three calls took 102 ms. If one rejects, the await throws, so your try/catch works again.

Need every result even when some fail? Use Promise.allSettled. The Promise APIs comparison covers the full set, and async/await is not parallel covers the sequential trap from the other side.

In practice#

The bug is quiet. Tests with fast mocks often pass, because the data arrives before anyone checks. In production it shows up as a save that "sometimes" misses rows, a response sent before the writes finish, or a serverless function that ends while the work is still running.

The same goes for filter, some and reduce with an async callback: they don't wait either. filter(async ...) keeps every item, because a promise is always truthy.

Say it in an interview: "forEach ignores the promise your async callback returns. It starts every call, returns undefined, and moves on, so code after it runs early and errors skip the try/catch. I use for...of when I need one at a time, or await Promise.all(items.map(...)) when they can run together."

Cheat sheet#

You wantUseWaits?
One at a time, in orderfor (const x of xs) await f(x)Yes
All together, all resultsawait Promise.all(xs.map(f))Yes
All together, keep failuresawait Promise.allSettled(xs.map(f))Yes
Fire and forget, on purposexs.forEach(f)No

TL;DR: forEach never waits for async callbacks. Use for...of for one at a time, or Promise.all with map for all at once.

Advanced · optional

Going deeper#

Everything above is enough to explain this in an interview. This part is for the curious: full numbers, edge cases and what's still unproven.

Why forEach can't wait#

The spec for Array.prototype.forEach calls the callback and ignores its return value. A sync function returns undefined, an async one returns a promise, and forEach treats both the same. Changing that would break every page that relies on it, so it stays.

Timings#

Measured on Node 22.18.0 with three fake calls of 100 ms each:

PatternResult right afterTotal time
forEach(async ...)[] at 0 msFull when checked at 150 ms, but nobody waited
for...of + await[1, 2, 3]303 ms
Promise.all(map)[1, 2, 3]102 ms

Limit how many run at once#

Promise.all over 10,000 items starts 10,000 requests. For large lists, process in chunks (for...of over slices, with Promise.all inside each one) or use a small pool library such as p-limit.

for await...of#

for await (const x of xs) is for async iterables, such as streams. On a plain array of promises it works, but it awaits them in order, and a rejection in a later promise can go unhandled while an earlier one is still pending. Prefer Promise.all for arrays.

Filed under#javascript#async-await#promises#foreach#interview

Series

Common Mistakes

Patterns that look fine in code review until production, the bundler, or an interview question proves otherwise.

  1. 1Barrel Files (`index.ts`): Why One Import Can Slow Your Build
  2. 2You Don't Need That useEffect: Derived State in React
  3. 3forEach and async/await: Why Your Loop Doesn't Wait · you are here
  4. 4The secret that NEXT_PUBLIC_ copied into git · coming soon

New parts land here first — subscribe below to get them in your inbox.

Was this worth your time?

One tap tells me what to write more of.

Mohsen Fallahnejad

Written by

Mohsen Fallahnejad

Frontend engineer explaining JavaScript, React & Next.js internals in posts you can finish over coffee. More about me

X ↗GitHub ↗LinkedIn ↗
← OlderWhat Runs First in a Next.js Page: Server Components, Render, Effects

Start the discussion

Questions, corrections, a better approach? I read and reply to every comment.

Read next

Boolean(x) vs !!x, Number vs parseInt, and String() vs toString()

Boolean and !! match. Number and + match, except a BigInt. String(null) is "null"; null.toString() throws.

Nov 17, 20268 min read

Hoisting and the TDZ: Why let Throws and var Is undefined

var and let are both registered when the scope starts. var is already undefined. let stays untouchable until its line runs.

Nov 16, 20265 min read

How Garbage Collection Works: It Never Looks for Unused Memory

The collector paints every object reachable from the stack and globals. Whatever the paint misses is unused, even if objects still point at each other.

Nov 16, 20267 min read

Get new posts in your inbox

One email when a new post is out: short, diagram-first explanations of JavaScript, React and Next.js. No spam, unsubscribe any time.

4 min left
Discuss👍 React
👍