AI basics & verificationPractical AI workflows

Why does an async forEach batch announce completion too early?

forEach does not wait for promises returned by async callbacks. Invoking two callbacks is not the same as finishing two tasks. Choose sequential or concurrent work, then make completion await the corresponding result; adding await before forEach is not a reliable repair.

Empty waiting-area chairs in sunlight
Illustrative photo: Anton Holmgren · Unsplash LicenseStock illustration, not a software screenshot, tested device or evidence of this exercise.

Key Takeaways

For independent tasks, collect promises with await Promise.all(names.map(work)); use a for...of loop with await for sequential dependencies. Both routes still need error handling, workload limits and result checks. The faulty specimen is authored teaching code, not an attributed model output or an actual file conversion.

In this article

Identify what the caller actually waits for

MDN documents forEach as returning undefined without waiting for promises. An await inside one callback controls that callback; the outer caller can continue. The work function below merely returns text after a delay; it imports or converts no file.

A separate editorial test used an explicitly released promise gate: results were empty before release and became A-ok and B-ok afterwards. This exposes ordering without a network-speed explanation. A fast task happening to finish in time does not prove that the caller awaits the right object.

Authored faulty specimen: report zero first

const names = ["A", "B"];
const work = async name => {
  await new Promise(resolve => setTimeout(resolve, 10));
  return name + "-ok";
};
const results = [];
names.forEach(async name => {
  results.push(await work(name));
});
console.log(results.length); // 0
The delay makes ordering visible; it is not a performance test. The callbacks have not finished when this message runs.

Choose waiting from the dependency rule

For a small pair of independent tasks, pass the promises returned by map to Promise.all and await the aggregate. Its result order follows the inputs, not completion order. Pass invoked work promises rather than function objects, and retain the callback return value.

If one result determines the next input, use a sequential loop. Even independent images or files should not automatically launch an unlimited workload at once; concurrency depends on the resources involved. This two-item exercise does not establish a universal concurrency limit.

Two explicit waiting routes

const together = await Promise.all(names.map(work));
console.log(together); // ["A-ok", "B-ok"]

const inOrder = [];
for (const name of names) {
  inOrder.push(await work(name));
}
console.log(inOrder); // ["A-ok", "B-ok"]
Run after defining work, in a module supporting top-level await. Equal results do not imply equal duration or resource use.

Aggregate rejection does not cancel sibling work

If B rejects, Promise.all rejects; A does not automatically stop if it already started. In the controlled check, A remained pending when B failed and still completed after its gate was released. Do not announce that all work stopped without an actual underlying cancellation mechanism and confirmed state.

When every item needs an outcome, choose per-item records or a mechanism such as allSettled according to the task. Before retrying, check whether successful work had side effects so it is not submitted twice. These synthetic tasks only return text and perform no business write.

Accept completion against actual results

Check empty input, two successes, one rejection and a dependent sequence. Retain input IDs, corresponding results and unfinished items. An empty batch may be acceptable or may violate the task; define that contract first.

The numeric-sort audit checks comparison, types and source mutation; this article checks the object awaited by the caller. Passing either does not establish the other. A reviewable request timeline separates started, running, succeeded and failed states so a completion label does not replace result evidence.

Further reading & sources

Newer articles on this topic

Continue with a newer article that refers to this guide or explainer.