Skip to content
JavaScript: Await each operation in a sequential batch

JavaScript: Await each operation in a sequential batch

November 18, 2026

An async callback passed to forEach can still be running when the surrounding function returns. Awaiting the result of forEach does not wait for those callbacks. Use an awaited loop when each save must finish before the next begins.

Set up

Tested on Debian 13 Linux with Node.js v24.19.0. Use Bash, Node.js on your PATH, a text editor, and the mktemp, rm and rmdir utilities. No packages or network access are needed. Keep the same terminal through cleanup. Stop if setup fails before saving the source.

start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1

Run the example

Save as javascript-await-sequential-work.mjs:

import assert from 'node:assert/strict';

const pending = Promise.withResolvers();
const completed = [];
const result = [1, 2].forEach(async id => {
  await pending.promise;
  completed.push(id);
});
assert.equal(result, undefined);
await result;
assert.deepEqual(completed, []);
console.log('Completed after awaiting forEach:', completed.length);
pending.resolve();
await pending.promise;
assert.deepEqual(completed, [1, 2]);

async function runInOrder(ids, save) {
  for (const id of ids) {
    await save(id);
  }
}

const saved = [];
await runInOrder([1, 2], async id => {
  await Promise.resolve();
  saved.push(id);
});
assert.deepEqual(saved, [1, 2]);
const attempted = [];
await assert.rejects(runInOrder([1, 2, 3], async id => {
  attempted.push(id);
  if (id === 2) throw new Error('save failed');
}), /save failed/);
assert.deepEqual(attempted, [1, 2]);
await runInOrder([], () => assert.fail('unexpected save'));
console.log('Saved in order:', saved.join(', '));
console.log('Attempts before failure:', attempted.join(', '));
console.log('Empty input: passed');

Run:

node javascript-await-sequential-work.mjs

Observed output:

Completed after awaiting forEach: 0
Saved in order: 1, 2
Attempts before failure: 1, 2
Empty input: passed

Why the first await finishes early

The first demonstration holds both callbacks on an unresolved promise. Its output is deterministic: awaiting the return value cannot release that promise. The example then releases the callbacks and checks their completion before continuing, so it leaves no unfinished work.

The ECMAScript forEach algorithm calls each callback and returns undefined. It does not collect the promises returned by async callbacks. Adding an await around the call therefore cannot turn those promises into a batch result.

Stop on the first failed operation

The awaited loop starts each save only after the preceding save fulfills. When the second save rejects, the loop rejects too; the third save is never called. A caller can catch that failure or let it propagate. Work already completed before a failure remains completed, so use a transaction or explicit compensation when the batch must be atomic.

The example uses in-memory arrays and intentionally caught errors. It performs no network or filesystem writes. The helper expects an iterable of IDs and a callback that returns a promise or a value. An operation that never settles also prevents the loop from progressing; cancellation and time limits need their own policy.

For independent operations that may overlap, collecting promises with map and awaiting Promise.all is a different choice. That starts all mapped operations, and a rejection does not cancel work already started. It also supplies no concurrency limit. Keep the sequential loop when ordering or stopping before the next operation is required.

Clean up

Remove the saved file and empty scratch directory. If the directory is not empty, inspect its contents before removing anything else.

rm -- javascript-await-sequential-work.mjs
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dir

Acknowledgements

This post was created with assistance from AI.

Last updated on