Skip to content
jshacks.dev
Async

Why You Should Not Await in a forEach Loop, and What to Use

Await in a forEach loop does not wait for anything. See why forEach ignores promises and which pattern to use instead: for...of, Promise.all or a pool.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, RabbitMQ and Apache Kafka logos.

The code looks right. An array of ids, an async callback, an await inside it, and a log line after the loop that says everything is done. Then the log line prints first, the work finishes later and errors vanish. The reason is that forEach was designed for synchronous callbacks and has no idea what an async function is. This post explains exactly why an await in a forEach loop does not pause anything outside the callback, shows the three situations the mistake produces, and gives the replacement for each: for...of when order matters, Promise.all with map when the work can run together, and a concurrency limit when it can run together but not all at once. The examples use Node.js 24 and apply to every current engine. If the promise model is new, the guide to how promises settle covers the foundations.

What forEach does with an async callback

Array.prototype.forEach calls your function once per element and ignores whatever it returns. An async function returns a promise, so the promise is thrown away. forEach itself returns undefined and finishes as soon as every callback has been started, which happens at the first await in each one.

foreach-bug.jsJavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function main() {
  [1, 2, 3].forEach(async (n) => {
    await sleep(50);
    console.log(`finished ${n}`);
  });
  console.log("loop done");
}

await main();
console.log("main done");
await sleep(100);
Text
loop done
main done
finished 1
finished 2
finished 3

loop done and main done print before any callback finishes. The await inside the callback pauses only that callback, and forEach has already moved to the next element and then returned. Anything you wrote after the loop that depends on the work, such as saving a total or closing a connection, runs too early.

Errors disappear

A rejected promise that nobody handles is an unhandled rejection. Because forEach discards the promises, a failure inside the callback cannot reach a try and catch around the loop.

foreach-errors.jsJavaScript
async function main() {
  try {
    [1, 2].forEach(async (n) => {
      throw new Error(`failed ${n}`);
    });
    console.log("no error caught");
  } catch (error) {
    console.log("caught", error.message);
  }
}

process.on("unhandledRejection", (reason) => {
  console.log("unhandled:", reason.message);
});

await main();
await new Promise((resolve) => setTimeout(resolve, 10));
Text
no error caught
unhandled: failed 1
unhandled: failed 2

The catch block never runs. Without the unhandledRejection listener, current Node.js versions would terminate the process with an error, which at least makes the bug loud. In a browser, the failures appear only as console warnings.

Fix 1: for...of when order matters

When each step must finish before the next starts, use a for...of loop. The await inside it pauses the enclosing async function, because the loop body is part of that function and not a separate callback.

for-of.jsJavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function main() {
  for (const n of [1, 2, 3]) {
    await sleep(20);
    console.log(`finished ${n}`);
  }
  console.log("loop done");
}

await main();
Text
finished 1
finished 2
finished 3
loop done

Now loop done comes last, errors reach a surrounding try and the total time is the sum of the steps. Use this form when later steps depend on earlier ones, when the target must receive calls in order, or when you want to stop at the first failure.

Fix 2: Promise.all with map when the work can overlap

If the iterations are independent, start them together and wait for all of them. map returns the array of promises that forEach threw away, and Promise.all waits for it.

promise-all.jsJavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function main() {
  const results = await Promise.all(
    [1, 2, 3].map(async (n) => {
      await sleep(50);
      return n * 10;
    })
  );
  console.log(results);
}

await main();
Text
[ 10, 20, 30 ]

All three waits ran at once, so the whole thing took about 50 milliseconds, not 150. The results come back in input order, regardless of which promise settled first. If one iteration rejects, Promise.all rejects immediately with that error, and the others keep running. To collect every outcome, use Promise.allSettled.

Fix 3: limit concurrency for large arrays

Promise.all over ten thousand items starts ten thousand tasks at once, which can exhaust sockets, memory or an API's rate limit. Process the array in groups, or use a pool, as shown in implementing Promise.all with a concurrency pool. A simple batching loop combines the two ideas.

batches.jsJavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function inBatches(items, size, worker) {
  const results = [];
  for (let i = 0; i < items.length; i += size) {
    const batch = items.slice(i, i + size);
    results.push(...(await Promise.all(batch.map(worker))));
  }
  return results;
}

const out = await inBatches([1, 2, 3, 4, 5], 2, async (n) => {
  await sleep(10);
  return n * 2;
});
console.log(out);
Text
[ 2, 4, 6, 8, 10 ]

Batches of two ran together, one batch after another. The weakness is that a slow item holds up its whole batch while other slots sit idle. A pool that starts the next item as soon as any slot frees is more efficient, and the queue in building an async queue does exactly that.

The same trap in other array methods

forEach is not alone. map, filter, some, every, reduce and find all expect synchronous callbacks. An async callback in filter returns a promise, which is truthy, so every element passes the filter. An async predicate in find always matches the first element for the same reason. When you need an async test, map to promises first, await them all, then filter on the results.

async-filter.jsJavaScript
const isEven = async (n) => n % 2 === 0;

const numbers = [1, 2, 3, 4];
const flags = await Promise.all(numbers.map(isEven));
console.log(numbers.filter((_, i) => flags[i]));
console.log(numbers.filter(isEven).length);
Text
[ 2, 4 ]
4

The second line shows the bug: filter(isEven) kept all four numbers, because each returned promise counts as truthy. Linting rules such as no-misused-promises flag these cases, and enabling them catches the mistake before it reaches a review.

Choosing between the fixes

Start from a question about the iterations: does one depend on another? If the third request needs the id returned by the second, or if the target system processes calls in order, the work is sequential and for...of is the only correct choice. If the iterations are independent, the next question is how many there are. A handful can all start at once with Promise.all. Hundreds or thousands need a limit, and the right limit comes from the slowest resource involved: a database connection pool of ten, an API that allows five requests per second, a disk that gains nothing past a few parallel reads.

A third question is what should happen when one iteration fails. With for...of inside a try, the first failure stops the loop and later items never run, which suits a transaction. With Promise.all, the first failure rejects the combined promise but leaves the other tasks running, which can be surprising if they have side effects. With Promise.allSettled, every task finishes and you decide afterward what to do with the failures, which suits batch jobs that should report all problems instead of stopping at the first.

Reviewing existing code

You can find this bug in a codebase with a search for forEach(async. Each hit deserves a look. Some are harmless, such as a callback whose async work is fire-and-forget on purpose, like sending analytics events, though even then the unhandled rejection risk remains and a catch inside the callback is wise. Most are real bugs waiting for the day the timing changes. The fix is usually mechanical: replace forEach with for...of and keep the body, or replace it with await Promise.all(items.map(...)). Add a test that asserts on a side effect that happens after the loop, such as a total that is written at the end, since that is the behavior the bug breaks.

Why the language works this way

forEach predates promises by many years. Its contract is to call a function for each element and return nothing, and changing it to wait for returned promises would break every existing program that returns a value from its callback by accident. The newer constructs fit async work because they were designed with it in mind: for await...of for async iterables, Promise.all for fan-out and top-level await in modules. Treat forEach as the tool for synchronous side effects and choose the others the moment an await appears in the body.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.