JavaScriptFundamental (ES6), part 1
Sequential vs parallel await in JavaScript
90 Sequential against parallel awaits, on a clock you inject
hardRun three dispatch trips of 100ms each, first with an await inside a loop and then with Promise.all, and read the finishing times off an injected clock rather than a real one. Then show that it is where you call the async function that decides, not where you await it, and that a genuinely dependent chain cannot be flattened.
Stuck? Three hints, smallest first
- 1. Give the clock a
wait(ms)that parks a resolver in a list, and anadvance(ms)that resolves the due ones in time order. - 2.
advancemust let pending microtasks run before it moves the time, or code that is mid-attempt registers its next wait against the wrong now and is stranded. - 3. Sequential is
for (const job of jobs) out.push(await job()). Parallel isPromise.all(jobs.map((job) => job()))— note that every call has happened before the first await.
const makeClock = () => {
let now = 0;
let waiting = [];
const drain = async () => {
for (let i = 0; i < 40; i++) await Promise.resolve();
};
return {
now: () => now,
wait(ms) {
return new Promise((resolve) => waiting.push({ at: now + ms, resolve }));
},
async advance(ms) {
const target = now + ms;
await drain(); // let waits register FIRST
let due = waiting.filter((w) => w.at <= target).sort((a, b) => a.at - b.at)[0];
while (due) {
waiting = waiting.filter((w) => w !== due);
now = due.at;
due.resolve();
await drain(); // whatever woke up may wait again
due = waiting.filter((w) => w.at <= target).sort((a, b) => a.at - b.at)[0];
}
now = target;
await drain();
},
};
};
const trip = (name, ms) => async (clock) => {
await clock.wait(ms);
return name + '@' + clock.now();
};
const sequential = async (clock, jobs) => {
const out = [];
for (const job of jobs) out.push(await job(clock));
return out;
};
const parallel = (clock, jobs) => Promise.all(jobs.map((job) => job(clock)));
const three = () => [trip('Ikeja', 100), trip('Yaba', 100), trip('Lekki', 100)];
const c1 = makeClock();
const seqRun = sequential(c1, three());
await c1.advance(300);
const seq = await seqRun;
const seqAt = c1.now();
const c2 = makeClock();
const parRun = parallel(c2, three());
await c2.advance(100);
const par = await parRun;
const parAt = c2.now();
const c3 = makeClock();
const held1 = trip('first', 100)(c3); // called now
const held2 = trip('second', 100)(c3); // called now as well
await c3.advance(100);
const bothStarted = [await held1, await held2, c3.now()];
const c4 = makeClock();
const mixedPar = parallel(c4, [trip('quick', 50), trip('slow', 250)]);
await c4.advance(250);
const mixedParOut = [await mixedPar, c4.now()];
const c5 = makeClock();
const mixedSeq = sequential(c5, [trip('quick', 50), trip('slow', 250)]);
await c5.advance(300);
const mixedSeqOut = [await mixedSeq, c5.now()];
const c6 = makeClock();
const cancelled = async (clock) => {
await clock.wait(30);
throw new Error('rider cancelled');
};
const guarded = Promise.all([cancelled(c6), trip('other', 200)(c6)]).catch((error) => error.message);
await c6.advance(30);
const failure = [await guarded, c6.now()];
const c7 = makeClock();
const lookupFare = async (clock, area) => {
await clock.wait(80);
return area === 'Lekki' ? 250000 : 120000;
};
const applyPromo = async (clock, kobo) => {
await clock.wait(20);
return kobo - 20000;
};
const chained = (async () => applyPromo(c7, await lookupFare(c7, 'Lekki')))();
await c7.advance(100);
const chainedOut = [await chained, c7.now()];
console.log('sequential:', seq, 'at', seqAt);
console.log('parallel :', par, 'at', parAt);
console.log('two calls :', bothStarted);
console.log('uneven :', mixedParOut, 'against', mixedSeqOut);
console.log('rejection :', failure, '| dependent chain:', chainedOut);
Output
9 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 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('awaited one at a time, each 100ms trip starts where the last one ended', seq, ['Ikeja@100', 'Yaba@200', 'Lekki@300']);
test('so the clock has moved by the sum of them', seqAt, 300);
test('started together, all three land at the same moment', par, ['Ikeja@100', 'Yaba@100', 'Lekki@100']);
test('and the clock has moved by one trip, not three', parAt, 100);
test('two awaits in a row are still parallel, because both calls already happened', bothStarted, ['first@100', 'second@100', 100]);
test('under Promise.all the cost is the longest job, not the total', mixedParOut, [['quick@50', 'slow@250'], 250]);
test('the same two in a loop cost the sum, and the second starts late', mixedSeqOut, [['quick@50', 'slow@300'], 300]);
test('a rejection surfaces the moment it happens, while the other is still waiting', failure, ['rider cancelled', 30]);
test('but a chain whose second step needs the first is the sum, and no combinator helps', chainedOut, [230000, 100]);
await in a loop is the most expensive habit in async JavaScript, and the fix is not to remove the awaits. Look at the two shapes: Promise.all(jobs.map((job) => job())) calls every function before awaiting anything, so all three trips are in flight at once. The loop calls the second function only after the first has resolved. The third assertion isolates it — two plain awaits one after another are fully parallel, because the calls that started the work both happened earlier. Awaiting does not start work; calling does.
The last assertion is the honest limit. When step two needs step one’s value, the total is the sum and no combinator can change that, so before reaching for Promise.all ask whether the items are genuinely independent. Where they are, the win is the difference between the maximum and the total, which is why the uneven pair costs 250 in parallel and 300 in sequence.
The clock is the technique that makes any of this testable. Real timers turn a test of backoff or a timeout into a test that sleeps, and sleeping tests get deleted. An injected clock with wait and advance turns elapsed time into an assertion about a number. One rule makes it work, and it is the second hint: advance must drain pending microtasks before moving the time forward. Move the clock first and code that is between two waits registers its next one against a now that has already jumped, so it is never due and the test hangs on a promise that will not settle.