JavaScriptFundamental (ES6), part 2
Start promises together, await in order in JavaScript
54 Start everything, then await in order
hardThere is a third shape between await in a loop and Promise.all: start every task, then await them in array order. Show that it overlaps the work and still returns results in order — then find the rejection it leaves unattended, and the two ways to fix that.
Stuck? Three hints, smallest first
- 1. A promise starts when it is created, not when it is awaited.
mapfirst,awaitsecond. - 2. Awaiting an already-settled promise costs a microtask and nothing else, so the loop order is free.
- 3. If the loop throws at index 1, nothing is ever attached to index 2.
const log = [];
const task = (name, rounds) => async () => {
log.push('start ' + name);
for (let i = 0; i < rounds; i++) await Promise.resolve();
log.push('end ' + name);
return name.toUpperCase();
};
const tasks = [task('a', 3), task('b', 1), task('c', 2)];
const oneAtATime = [];
for (const start of tasks) oneAtATime.push(await start());
const sequentialLog = log.slice();
log.length = 0;
const started = tasks.map((start) => start());
const startedAtOnce = log.slice();
const inOrder = [];
for (const running of started) inOrder.push(await running);
const overlappedLog = log.slice();
const viaAll = await Promise.all(started);
const nothingReran = log.slice();
let attempts = 0;
const fails = (name) => async () => { attempts++; await Promise.resolve(); throw new Error(name + ' failed'); };
const risky = [task('ok', 1)(), fails('b')(), fails('c')()];
let stoppedAt = '';
try { for (const running of risky) await running; }
catch (err) { stoppedAt = err.message; }
const handledLate = await risky[2].then(() => 'resolved', (err) => 'handled late: ' + err.message);
const everyOutcome = (await Promise.allSettled(risky)).map((r) => r.status);
console.log('one at a time :', sequentialLog);
console.log('all started :', startedAtOnce);
console.log('then awaited :', overlappedLog);
console.log('loop stopped :', stoppedAt, '- index 2:', handledLate);
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 inside the loop runs them strictly one at a time', sequentialLog, ['start a', 'end a', 'start b', 'end b', 'start c', 'end c']);
test('mapping first starts all three before anything is awaited', startedAtOnce, ['start a', 'start b', 'start c']);
test('so they finish by duration, not by position', overlappedLog.slice(3), ['end b', 'end c', 'end a']);
test('yet the results come back in array order', inOrder, ['A', 'B', 'C']);
test('Promise.all over the same promises gives the same values and starts nothing new', [viaAll, nothingReran.length], [['A', 'B', 'C'], 6]);
test('a rejection at index 1 ends the loop, leaving index 2 unattended', [stoppedAt, attempts], ['b failed', 2]);
test('that promise is still rejected, and can be handled later', handledLate, 'handled late: c failed');
test('allSettled is the shape that attaches a handler to every one', everyOutcome, ['fulfilled', 'rejected', 'rejected']);
The distinction that makes this work: a promise begins its work when it is created. tasks.map(start => start()) starts all three in one synchronous pass, and the awaits afterwards are just collection. You get the concurrency of Promise.all with results in array order and no wrapper — useful when you want to process each result as its turn comes rather than assembling one array at the end.
The sixth and seventh assertions are why this shape needs care. When index 1 rejects, the loop throws and index 2's promise is left with no handler at all — nobody ever awaited it. It is still rejected, and it can be handled later, but in Node an unhandled rejection that survives the tick exits the process non-zero, and in a browser it hits window.onunhandledrejection. So the failure mode is not a lost value, it is a crash somewhere unrelated.
Two fixes, both one line. Attach a catch when you start them — const p = start(); p.catch(() => {}); — if you intend to read the failures later. Or hand the whole array to Promise.all or allSettled, both of which attach a handler to every input immediately, which is the real reason they are the safer default. allSettled when each task stands alone, all when one failure voids the lot.
Worth noting what the fifth assertion proves: Promise.all over promises that have already been awaited does not re-run anything — the log is still six lines. A promise is a value, not a task, so awaiting it twice is free.