LESSON 15 / 16·2 min readIntermediate

Why does forEach with async cause problems?

Try code in the playground
01 Understand02 Recall03 Prepare

Understand the concept

forEach calls a callback for each array item but ignores the values returned by those callbacks. An async callback returns a promise, so forEach does not wait for its completion or collect its rejection. Choose a loop or a promise combinator based on whether the operations depend on each other.

Important ideas

  • forEach does not wait for promises returned by its callback.

  • Use for...of with await for one task at a time.

  • Use Promise.all(items.map(...)) for a small batch; limit concurrency for large batches.

  • A surrounding await items.forEach(...) does not fix the issue because forEach returns undefined.

  • Sequential work is appropriate when order matters; concurrent work is appropriate only when operations are independent and resources can handle it.

Work through the example

JavaScript
async function demo() {
  const save = async id => `saved ${id}`;
  const ids = [1, 2];
  for (const id of ids) {
    console.log(await save(id)); // One operation at a time.
  }
  const results = await Promise.all(ids.map(save));
  console.log(results); // ['saved 1', 'saved 2']
}
demo();
  • The second approach starts the small independent batch together; a large real batch needs a concurrency limit.
PAUSE & RECALL

Can you explain it without the notes?

Why does forEach with async cause problems?

Use your own words. Explain an example and one limitation before checking the explanation.

Check your explanation

forEach calls a callback for each array item but ignores the values returned by those callbacks. An async callback returns a promise, so forEach does not wait for its completion or collect its rejection. Choose a loop or a promise combinator based on whether the operations depend on each other.

CONNECT IT TO YOUR INTERVIEW

Turn this concept into a clear answer.

  • The question is both “does the caller wait?” and “how much work starts at once?”
Practice this concept
YOUR NEXT STEP

Keep connecting the ideas.

Next lesson: What causes a race condition?

Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “Why does forEach with async cause problems?”. Examples are study fragments; framework behavior can depend on your version.