JavaScriptFundamental (ES6), part 2
Promise timeout that cancels the work in JavaScript
53 A timeout that actually cancels
hardExercise 23's timeout left the work running and the timer pending. Fix both: pass the work a cancellation token, clear the timer in a finally, and prove the abandoned work stops at its next check. Then show what happens to work that ignores the token.
Stuck? Three hints, smallest first
- 1. The token from exercise 33, plus the race from exercise 23. The timer cancels the token before it rejects.
- 2. Hold on to the running promise and attach a
catchto it, or the loser becomes an unhandled rejection. - 3. Clear the timer in a
finally, which is whatclearTimeoutis for in real code.
function manualClock() {
let now = 0;
const timers = [];
return {
get time() { return now; },
get pending() { return timers.length; },
wait(ms) {
const timer = { at: now + ms };
const promise = new Promise((resolve) => { timer.resolve = resolve; });
timers.push(timer);
promise.clear = () => { // the clearTimeout handle
const at = timers.indexOf(timer);
if (at !== -1) timers.splice(at, 1);
};
return promise;
},
async advance(ms) {
now += ms;
for (const timer of timers.filter((t) => t.at <= now)) {
timers.splice(timers.indexOf(timer), 1);
timer.resolve();
}
for (let i = 0; i < 20; i++) await Promise.resolve();
},
};
}
class CancelledError extends Error {
constructor(reason) { super(reason); this.name = 'CancelledError'; }
}
function cancellation() {
let cancelled = false;
let reason = '';
return {
get cancelled() { return cancelled; },
get reason() { return reason; },
throwIfCancelled() { if (cancelled) throw new CancelledError(reason); },
cancel(why) { if (cancelled) return false; cancelled = true; reason = why; return true; },
};
}
async function withDeadline(work, ms, clock) {
const token = cancellation();
const running = work(token);
running.catch(() => {}); // the loser must not go unhandled
const timer = clock.wait(ms);
const expired = timer.then(() => {
token.cancel(`deadline of ${ms}ms passed`);
throw new Error(`timed out after ${ms}ms`);
});
expired.catch(() => {});
try {
return await Promise.race([running, expired]);
} finally {
timer.clear(); // no timer left pending
token.cancel('work finished'); // no work left running
}
}
const clock = manualClock();
const steps = [];
const payTills = async (token) => {
for (const till of ['ikeja', 'yaba', 'lekki', 'ajah']) {
token.throwIfCancelled();
await clock.wait(100);
steps.push(till);
}
return 'all four paid';
};
const outcome = withDeadline(payTills, 250, clock).then((v) => v, (err) => err.message);
await clock.advance(100);
await clock.advance(100);
const atTheDeadline = steps.slice();
await clock.advance(50);
const timedOut = await outcome;
await clock.advance(100);
const afterTheInFlightStep = steps.slice();
await clock.advance(500);
const nothingMore = steps.slice();
const timersLeft = clock.pending;
const second = manualClock();
const quickSteps = [];
const payOne = async (token) => {
await second.wait(50);
token.throwIfCancelled();
quickSteps.push('paid');
return 'paid in time';
};
const winner = withDeadline(payOne, 500, second).then((v) => v, (err) => err.message);
await second.advance(50);
const won = await winner;
const noLeak = second.pending;
const third = manualClock();
const stubbornSteps = [];
const ignoresTheToken = async () => {
for (const till of ['ikeja', 'yaba', 'lekki']) {
await third.wait(100);
stubbornSteps.push(till);
}
return 'finished anyway';
};
const abandoned = withDeadline(ignoresTheToken, 150, third).then((v) => v, (err) => err.message);
await third.advance(100);
await third.advance(50);
const gaveUpAt = await abandoned;
await third.advance(100);
await third.advance(100);
const keptGoing = stubbornSteps.slice();
console.log('timed out :', timedOut, 'with', atTheDeadline, 'done');
console.log('then one more :', afterTheInFlightStep, '-> and stopped:', nothingMore);
console.log('work won :', won, '- timers left:', noLeak);
console.log('token ignored :', gaveUpAt, '- work did', keptGoing);
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('the caller gets the timeout at the deadline', timedOut, 'timed out after 250ms');
test('two steps had finished by then', atTheDeadline, ['ikeja', 'yaba']);
test('the step already in flight still lands, because nothing interrupts it', afterTheInFlightStep, ['ikeja', 'yaba', 'lekki']);
test('but the fourth never starts: the token stopped it, unlike exercise 23', nothingMore, ['ikeja', 'yaba', 'lekki']);
test('and no timer is left pending either', timersLeft, 0);
test('when the work wins, the caller gets its value', [won, quickSteps], ['paid in time', ['paid']]);
test('and the deadline timer is cleared rather than left to fire', noLeak, 0);
test('work that ignores the token cannot be stopped, only abandoned', [gaveUpAt, keptGoing], ['timed out after 150ms', ['ikeja', 'yaba', 'lekki']]);
This is exercise 23 with both leaks closed, and it takes two separate fixes because they are two separate leaks. timer.clear() in the finally is clearTimeout: without it a won race leaves a pending timer holding a closure, and in Node a pending timer also keeps the process alive. token.cancel() is the other half: the work is told to stop, so the fourth step never starts.
The third and fourth assertions are the honest limit, and they are the same granularity point exercise 33 makes. Cancellation is co-operative, so the step already awaiting its 100ms carries on to completion — you cannot un-send a request. What you can do is make sure nothing further is attempted, which is the difference between abandoning three units of work and abandoning all four.
The last assertion is what happens without co-operation, and it is the common case in real code: work that never checks the token runs to completion, produces a value nobody receives, and holds its connection the whole time. The caller cannot tell the difference — both cases reject with the same timeout — which is why the leak is invisible until the connection pool is exhausted. AbortSignal is the platform's version of this contract, and passing a signal to fetch works only because fetch was written to honour it.
One line that looks redundant and is not: running.catch(() => {}). When the timer wins, the work's own rejection has no handler attached, and an unhandled rejection in Node exits the process non-zero. Attaching an empty handler says "somebody has looked at this", which is exactly true — the race already reported the outcome the caller cares about.