JavaScriptFundamental (ES6), part 2
Why await in a loop runs serially in JavaScript
26 Why await in a loop serialises
hardRun the same three async tasks two ways — await inside a for...of, and Promise.all over a map — and log every start and end. Compute the peak concurrency of each. Then find the case where the loop is the correct shape, and the one where forEach is neither.
Stuck? Three hints, smallest first
- 1. Have each task log on entry and on exit, then read the interleaving off the log.
- 2. Peak concurrency: walk the log, add one for a start and subtract one for an end, keep the maximum.
- 3.
forEachignores the promise its callback returns, so nothing awaits anything.
const makeTask = (log) => async (name, rounds) => {
log.push('start ' + name);
for (let i = 0; i < rounds; i++) await Promise.resolve();
log.push('end ' + name);
return name.toUpperCase();
};
const peakOf = (log) => {
let inFlight = 0;
let peak = 0;
for (const line of log) {
if (line.startsWith('start')) peak = Math.max(peak, ++inFlight);
else inFlight--;
}
return peak;
};
const seqLog = [];
const seqTask = makeTask(seqLog);
const seqOut = [];
for (const name of ['a', 'b', 'c']) seqOut.push(await seqTask(name, 2));
const parLog = [];
const parTask = makeTask(parLog);
const parOut = await Promise.all(['a', 'b', 'c'].map((name) => parTask(name, 2)));
// When each step needs the one before it, the loop is right.
const chain = [];
let carry = 1;
for (const factor of [2, 3, 4]) { carry = await Promise.resolve(carry * factor); chain.push(carry); }
// forEach does not await, so this collects nothing at all.
const dropped = [];
['a', 'b'].forEach(async (v) => { await Promise.resolve(); dropped.push(v); });
const droppedNow = [...dropped];
console.log('sequential:', seqLog);
console.log('parallel :', parLog);
console.log('peaks :', peakOf(seqLog), 'against', peakOf(parLog));
console.log('forEach right after the loop:', droppedNow);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('awaiting in a loop runs them one after another', seqLog, ['start a', 'end a', 'start b', 'end b', 'start c', 'end c']);
test('Promise.all starts all three before any of them finishes', parLog, ['start a', 'start b', 'start c', 'end a', 'end b', 'end c']);
test('peak concurrency: one against three', [peakOf(seqLog), peakOf(parLog)], [1, 3]);
test('both produce the same results in the same order', [seqOut, parOut], [['A', 'B', 'C'], ['A', 'B', 'C']]);
test('so the difference is time, not correctness, for independent work', seqOut.join('') === parOut.join(''), true);
test('when each step needs the last, the loop is the correct shape', chain, [2, 6, 24]);
test('forEach ignores the promise, so nothing has happened yet', droppedNow, []);
test('though the pushes do land eventually, unordered and unawaited', await (async () => { await Promise.resolve(); await Promise.resolve(); return dropped.length; })(), 2);
await means "stop this function here". In a loop that is once per iteration, so n independent requests of 200ms each take 200n milliseconds, and the log shows why: end a before start b. Promise.all over a map starts all of them in the synchronous pass and then waits once, so the same work takes as long as the slowest one.
The peak-concurrency assertion is the whole diagnosis in one number. One against three. That is also the reason to be careful: Promise.all over ten thousand items opens ten thousand connections at once, which is a different outage. Exercise 21's mapLimit is the middle ground, and in production it is nearly always the right answer.
The sixth assertion is the exception that keeps the loop honest. When each step consumes the previous result, there is nothing to parallelise and await in a loop is not a mistake — it is the only correct shape. Rewriting that as Promise.all would compute all three from the same starting value.
forEach is in a category of its own. It has no return value and does not look at the one the callback gives it, so an async callback returns a promise into the void: the loop finishes instantly, the work happens later, and errors inside become unhandled rejections. Use for...of to serialise or map plus Promise.all to parallelise, and never forEach with async.