Coordinate asynchronous work

Why JavaScript forEach Cannot Break or Wait for Async Callbacks

See why forEach ignores callback returns and does not wait for async callbacks, with examples for early exit and retaining job promises.

Editorial illustration for Why JavaScript forEach Cannot Break or Await Async Callbacks

If reaching one job must prevent later jobs from being visited, use a loop with break, not forEach. If each visit starts asynchronous work that later code needs to track, keep the job promises separately. An await inside an async callback can wait within that callback, but it does not make forEach wait or change its undefined result.

Run these blocks in order in a JavaScript environment that supports async functions and console.log. They use one array throughout. The job function below is a small teaching example, not a network request.

What forEach passes to each callback and what it returns

forEach calls its callback once for each assigned array index, in ascending-index order. Each call receives the element, its index and the array being visited:

const jobs = ["draft", "publish", "archive"];

const result = jobs.forEach((job, index, array) => {
  console.log(index, job, array === jobs);
});

console.log(result);

The output is:

0 draft true
1 publish true
2 archive true
undefined

The final undefined is the result of forEach, not a missing job. The third callback argument is the same jobs array, which is why each comparison prints true. The MDN forEach reference documents those arguments and the method's return value. It also notes an important boundary: an empty slot in a sparse array gets no callback. This example has three assigned indices, so it visits all three.

Why returning from a callback cannot stop the next visit

A callback can return a value, but forEach discards it. Even an explicit return at the selected job ends only that callback invocation:

const visitedByForEach = [];

jobs.forEach((job) => {
  visitedByForEach.push(job);
  if (job === "publish") return;
});

console.log(visitedByForEach); // ["draft", "publish", "archive"]

archive is still visited. That matters if each visit starts a job: the return does not keep the later job from being started. Moving the return earlier in the callback could skip other statements for publish, but it would not turn the callback into a loop with an exit condition.

A bare break inside a forEach callback is a syntax error, not a way to exit the call. MDN says the way to stop forEach early is to throw an exception, and advises against using it when ordinary early termination is needed. An indexed loop makes the stopping condition explicit:

const visitedByLoop = [];

for (let index = 0; index < jobs.length; index += 1) {
  const job = jobs[index];
  visitedByLoop.push(job);
  if (job === "publish") break;
}

console.log(visitedByLoop); // ["draft", "publish"]

This loop records publish, then stops before reaching archive. The contrast is about control flow, not about changing what return means inside the callback. Choose this form when visiting archive would start work that should not start after publish is reached.

Why await inside an async callback does not make forEach wait

The discarded-return rule also matters for async callbacks. MDN states that forEach does not wait for promises. Here, each callback saves its job promise, logs the saved entry and then awaits that promise internally:

async function runJob(job) {
  return `done: ${job}`;
}

const promises = [];

const asyncResult = jobs.forEach(async (job, index) => {
  const promise = runJob(job);
  promises[index] = promise;
  console.log("saved", index, job);
  await promise;
});

console.log(asyncResult);
console.log(promises.length);

The logs identifying saved entries appear for indices 0, 1 and 2, followed by undefined and 3. The await promise belongs to each callback. It does not turn the surrounding forEach call into an operation that waits for those callbacks. In particular, asyncResult is undefined, not a completion promise for the jobs. Saving the promises also does not, by itself, wait for completion; it gives later code access to the promises that runJob produced.

Choose a loop for early exit or retain promises for later tracking

Use the indexed loop when reaching publish must prevent a visit to archive. Use forEach when visiting each assigned index is acceptable and no decision depends on a callback's return value. If later code needs access to asynchronous jobs, save their promises as the last example does rather than expecting forEach to return them.

These choices solve different problems. The loop controls which jobs are visited. The saved array preserves references to promises for jobs that were visited. Neither an internal await nor putting await in front of the forEach call makes its undefined result a promise that tracks all the callbacks.

Find a note

Search by topic, title, or keyword.