JavaScriptInterview preparation
Intermediate·Concept·2 min read

Why does forEach with async cause problems?

Practice this question

Definition:

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.

Key points:

  • 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.

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.

Interview point:

  • The question is both “does the caller wait?” and “how much work starts at once?”
Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “Why does forEach with async cause problems?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.