Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Cancellation token in JavaScript

33 A cancellation token, honoured co-operatively

hard

Build the token exercise 23 said was missing: cancel(reason), a cancelled flag, throwIfCancelled() and onCancel(fn). Have a multi-step job check it between steps. Then show the limit of the whole idea — a step already in flight carries on regardless.

Stuck? Three hints, smallest first
  1. 1. A token is state plus listeners. It has no power over anything: the work has to ask.
  2. 2. Cancelling twice must not fire the listeners twice, and the first reason is the one that counts.
  3. 3. Register a listener after the cancel and it should fire straight away, or a late subscriber hangs for ever.

The answer

class CancelledError extends Error {
  constructor(reason) {
    super(reason);
    this.name = 'CancelledError';
  }
}

function cancellation() {
  let cancelled = false;
  let reason = '';
  const listeners = [];
  return {
    get cancelled() { return cancelled; },
    get reason() { return reason; },
    throwIfCancelled() { if (cancelled) throw new CancelledError(reason); },
    onCancel(fn) { if (cancelled) fn(reason); else listeners.push(fn); },
    cancel(why) {
      if (cancelled) return false;                       // the first cancel wins
      cancelled = true;
      reason = why;
      for (const fn of listeners.splice(0)) fn(why);
      return true;
    },
  };
}

// The work co-operates: it checks the token before each unit of work.
async function payOut(tills, token, onStep) {
  const paid = [];
  for (const till of tills) {
    token.throwIfCancelled();
    await Promise.resolve();                             // the transfer
    paid.push(till);
    if (onStep) onStep(till);
  }
  return paid;
}

const token = cancellation();
const notified = [];
token.onCancel((why) => notified.push(why));

const seen = [];
const outcome = await payOut(['ikeja', 'yaba', 'lekki', 'ajah'], token, (till) => {
  seen.push(till);
  if (till === 'yaba') token.cancel('user closed the tab');
}).catch((err) => err);

const secondCancel = token.cancel('a different reason');
let lateSubscriber = 'never told';
token.onCancel((why) => { lateSubscriber = why; });

const dead = cancellation();
dead.cancel('cancelled before it started');
const never = [];
const nothingRan = await payOut(['ikeja'], dead, (till) => never.push(till)).catch((err) => err.name);

// The honest limit: cancelling mid-step does not interrupt that step.
const late = cancellation();
const finished = [];
const inFlight = (async () => {
  late.throwIfCancelled();
  await Promise.resolve();
  finished.push('the step that was already running');
  late.throwIfCancelled();
  finished.push('a step that never starts');
})().catch((err) => err.name);
late.cancel('too late for the step in flight');
const interrupted = await inFlight;

console.log('paid before the cancel :', seen);
console.log('outcome                :', outcome.name + ': ' + outcome.message);
console.log('already cancelled      :', nothingRan, '- steps run:', never.length);
console.log('mid-step cancel        :', interrupted, finished);

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.

8 checks

test('the work stops at the first check after the cancel', seen, ['ikeja', 'yaba']);
test('and the caller gets a CancelledError carrying the reason', [outcome.name, outcome.message], ['CancelledError', 'user closed the tab']);
test('which is a real Error subclass, so instanceof holds', [outcome instanceof CancelledError, outcome instanceof Error], [true, true]);
test('a token cancelled up front stops the job before step one', [nothingRan, never], ['CancelledError', []]);
test('listeners fire exactly once, with the reason', notified, ['user closed the tab']);
test('a listener registered afterwards fires immediately instead of hanging', lateSubscriber, 'user closed the tab');
test('the second cancel is ignored and the first reason stands', [secondCancel, token.reason], [false, 'user closed the tab']);
test('but a step already in flight runs to the end: only the next check stops', [finished, interrupted], [['the step that was already running'], 'CancelledError']);

A token has no authority. It is a flag, a reason and a list of listeners, and nothing happens unless the work asks — which is why throwIfCancelled() sits at the top of the loop body. This is exactly how the platform's own AbortController works: signal.aborted, signal.reason, addEventListener(‘abort’). fetch honours it because fetch was written to; a function that ignores the signal is unaffected by it.

The last assertion is the boundary worth internalising, and it is the answer to the leak in exercise 23. Cancellation is granular to the checks you wrote. Between two checks the work is uninterruptible, so a long single step — one enormous query, one large upload — cannot be cancelled at all, no matter how many tokens you thread through. Cutting a job into steps is what makes it cancellable.

Two details that look like fussiness and are not. cancel returning false the second time keeps the reason stable, so the error message does not depend on who cancelled last. And onCancel firing immediately when the token is already cancelled removes an entire class of race: a subscriber that arrives one microtask late would otherwise wait for an event that has already happened.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.