JavaScriptFundamental (ES6), part 1
Cancel async work with AbortController in JavaScript
114 cancelling work with an AbortController
hardMake a multi-step transfer cancellable with an AbortController. Each step waits on an injected clock, and the wait must lose a race against the abort. Show what happens when the signal is already aborted before you start, what a bare abort() throws, and that the abandoned wait still fires.
Stuck? Three hints, smallest first
- 1. A cancellable wait is a race: one
Promisewhoseresolvethe clock calls and whoserejectthe abort event calls. - 2. Check
signal.abortedbefore subscribing. A signal that is already aborted will never fire the event again, so the listener alone is not enough. - 3.
signal.reasonis whatever you passed toabort(...), and with no argument it is aDOMExceptionnamedAbortError.
const makeClock = () => {
let now = 0;
let seq = 0;
const timers = [];
const drainMicrotasks = async () => {
for (let i = 0; i < 50; i++) await Promise.resolve();
};
return {
now: () => now,
wait: (ms) => new Promise((resolve) => timers.push({ at: now + ms, seq: seq++, resolve })),
async runAll() {
await drainMicrotasks(); // microtasks first, then move the clock
while (timers.length) {
timers.sort((a, b) => a.at - b.at || a.seq - b.seq);
const next = timers.shift();
now = next.at;
next.resolve();
await drainMicrotasks();
}
return now;
},
};
};
const waitOrAbort = (clock, ms, signal) =>
new Promise((resolve, reject) => {
if (signal.aborted) {
reject(signal.reason); // already cancelled: the event will not fire again
return;
}
const onAbort = () => reject(signal.reason);
signal.addEventListener('abort', onAbort, { once: true });
clock.wait(ms).then(() => {
signal.removeEventListener('abort', onAbort);
resolve();
});
});
const steps = [
{ name: 'reserve stock', ms: 10 },
{ name: 'charge card', ms: 20 },
{ name: 'notify rider', ms: 5 },
];
const runTransfer = async ({ abortAt = null, abortFirst = false }) => {
const clock = makeClock();
const controller = new AbortController();
const signal = controller.signal;
const done = [];
const transfer = async () => {
for (const step of steps) {
await waitOrAbort(clock, step.ms, signal);
done.push(step.name);
}
return done.join(' -> ');
};
if (abortFirst) controller.abort(new Error('cancelled before we started'));
else if (abortAt !== null) clock.wait(abortAt).then(() => controller.abort(new Error('rider cancelled')));
let value = 'no value';
let failure = 'no error';
const settled = transfer().then((v) => { value = v; }, (e) => { failure = e.message; });
await clock.runAll();
await settled;
return { value, failure, done, at: clock.now(), controller };
};
const whole = await runTransfer({});
const cancelled = await runTransfer({ abortAt: 25 });
const early = await runTransfer({ abortFirst: true });
whole.controller.abort(new Error('too late to matter'));
const afterTheFact = [whole.value, whole.controller.signal.aborted, whole.controller.signal.reason.message];
const bare = new AbortController();
bare.abort();
const defaultReason = [bare.signal.aborted, bare.signal.reason.name];
const twice = new AbortController();
twice.abort(new Error('first reason'));
twice.abort(new Error('second reason'));
const keptReason = twice.signal.reason.message;
console.log('whole :', whole.value, '| clock:', whole.at);
console.log('cancelled:', cancelled.done, '->', cancelled.failure, '| clock:', cancelled.at);
console.log('early :', early.done, '->', early.failure, '| clock:', early.at);
console.log('bare :', defaultReason, '| kept:', keptReason);
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('with nobody cancelling, every step ran and the clock advanced 35', [whole.value, whole.at], ['reserve stock -> charge card -> notify rider', 35]);
test('an abort at 25 stops it after the step that had already finished', [cancelled.done, cancelled.failure], [['reserve stock'], 'rider cancelled']);
test('the wait that lost the race still fired at 30, with nobody listening', cancelled.at, 30);
test('a signal that is already aborted fails before any work and never touches the clock', [early.done, early.failure, early.at], [[], 'cancelled before we started', 0]);
test('aborting afterwards flips the signal and changes nothing else', afterTheFact, ['reserve stock -> charge card -> notify rider', true, 'too late to matter']);
test('abort() with no argument gives a DOMException named AbortError', defaultReason, [true, 'AbortError']);
test('aborting twice keeps the first reason', keptReason, 'first reason');
test('a controller owns exactly one signal, which is the handle you pass around', [whole.controller.signal === whole.controller.signal, typeof whole.controller.signal.addEventListener], [true, 'function']);
AbortController is a one-way switch with an event attached, and the split between the two halves is the useful part: you keep the controller, callers get the signal. A signal can only be read and listened to, so handing one out gives away the ability to observe cancellation without the ability to cause it. That is why fetch, the streams API and Node's own APIs all take a signal rather than a controller.
The aborted check before subscribing is not defensive noise. An abort that has already happened will never fire the event again, so a listener-only implementation waits for ever on a signal that was cancelled a moment before it was passed in — which is exactly what happens when a signal is reused or created from a parent. Both paths have to reject, and both have to reject with signal.reason so callers can tell cancellation from failure.
Two things the assertions expose. The abandoned wait still fires: rejecting the race does nothing to the timer underneath, so the clock still ran to 30 and, with a real setTimeout, a handle would still be sitting in the event loop. Cancellation has to clear the timeout, not just stop caring about it, or a busy cancelled path leaks timers and keeps the process awake. And abort() with no argument produces a DOMException named AbortError, which is the string every caller checks against to decide "this was cancelled" rather than "this went wrong" — so if you pass your own reason, keep that distinction visible.