JavaScriptFundamental (ES6), part 2
Async task queue that survives failures in JavaScript
27 An async queue that survives a failure
hardBuild a queue that runs added tasks strictly one at a time in the order they arrived. Each add hands back a promise for its own task's result. A task that throws must reject only its own caller and must not block the queue.
Stuck? Three hints, smallest first
- 1. Keep a
tailpromise. Each new task chains off it, and becomes the new tail. - 2. The tail must be built from a chain that swallows failures, or one rejection stops everything after it.
- 3. The promise you return to the caller is not the same promise you keep as the tail.
class AsyncQueue {
#tail = Promise.resolve();
#pending = 0;
get pending() { return this.#pending; }
add(task) {
this.#pending++;
const result = this.#tail.then(() => task());
// The tail must absorb failures, or one bad task blocks the queue for ever.
this.#tail = result.then(
() => { this.#pending--; },
() => { this.#pending--; }
);
return result;
}
drain() { return this.#tail; }
}
const log = [];
const step = (name, rounds) => async () => {
log.push('start ' + name);
for (let i = 0; i < rounds; i++) await Promise.resolve();
log.push('end ' + name);
return name;
};
const q = new AsyncQueue();
const results = await Promise.all([q.add(step('a', 3)), q.add(step('b', 1)), q.add(step('c', 0))]);
const failLog = [];
const q2 = new AsyncQueue();
const bad = q2.add(async () => { failLog.push('bad'); throw new Error('kaboom'); }).catch((e) => e.message);
const good = q2.add(async () => { failLog.push('good'); return 'ran anyway'; });
const outcome = [await bad, await good];
const counting = new AsyncQueue();
counting.add(async () => 1);
counting.add(async () => 2);
const whileBusy = counting.pending;
await counting.drain();
const whenDrained = counting.pending;
const syncLog = [];
const q3 = new AsyncQueue();
q3.add(() => { syncLog.push('sync task'); return 'done'; });
const beforeDrain = [...syncLog];
await q3.drain();
console.log('order :', log);
console.log('results :', results);
console.log('failure :', outcome, failLog);
console.log('pending :', whileBusy, '->', whenDrained);
Output
7 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 7 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('tasks run one at a time, in the order they were added', log, ['start a', 'end a', 'start b', 'end b', 'start c', 'end c']);
test('each add() gives back its own result', results, ['a', 'b', 'c']);
test('a failure is reported to its own caller only', outcome, ['kaboom', 'ran anyway']);
test('and the queue carried on past it', failLog, ['bad', 'good']);
test('pending counts what is outstanding', whileBusy, 2);
test('and drops to zero once drained', whenDrained, 0);
test('even a synchronous task is deferred to a microtask', [beforeDrain, syncLog], [[], ['sync task']]);
The queue is one promise. tail is "everything added so far has finished", and adding a task means chaining off it and replacing it. No array of jobs, no loop, no flag saying whether it is running.
The subtlety is that add maintains two promises from one task. result is what the caller gets, and it rejects if the task throws. The new tail is result.then(dec, dec), which has a handler on both sides and therefore always fulfils. Keep result as the tail instead and the third assertion fails hard: the rejection propagates into every task chained after it and the queue is dead for the rest of the process. That is the bug this exercise exists to show.
It also means a queue is a semaphore with one permit, and if you have written exercise 29 you can build this from it in three lines. Keep them apart when the two-promise trick is what you need to remember.
The last assertion is a promise property, not a queue one: this.#tail.then(() => task()) defers even an entirely synchronous task to a microtask. Consistent, and occasionally surprising when you expected the push to have happened by the next line.