Sub topic 1
Why Your Async Functions Should Be Cancellable
Prerequisites
This chapter assumes you know JavaScript functions, closures, and destructuring. It also assumes you can use promises with async/await, handle errors with try/catch, and attach handlers with addEventListener. You should have used setTimeout and fetch before.
Why Your Async Functions Should Be Cancellable
Async work often outlives the reason it was started. A user leaves a page, types a new search term, or closes a dialog. If the old work keeps running, it wastes network and CPU time. It can also write stale results into your UI. A cancellable function lets the caller say "stop" and get a clear, predictable result.
AbortController and AbortSignal in One Minute
The platform splits cancellation into two objects:
- An
AbortControlleris held by the caller, the code that decides when to cancel. Callingcontroller.abort()triggers cancellation. - An
AbortSignal(controller.signal) is handed to the work. The work can read it and listen to it, but it cannot trigger cancellation.
Because of this split, a function that receives only the signal can never cancel other code that shares that signal.
Reading a Signal: aborted and reason
A signal has two properties that matter here:
signal.abortedisfalseuntilabort()is called. After that it istrue, and it never resets.signal.reasonisundefineduntil the signal aborts. Ifabort()is called with no argument, the reason is aDOMExceptionnamed"AbortError".
Reacting to the abort Event
The signal fires an abort event once, at the moment of cancellation. Use { once: true } so the handler does not stay attached after it runs.
const controller = new AbortController();
const { signal } = controller;
signal.addEventListener('abort', () => {
console.log('aborted:', signal.aborted); // true
console.log('reason:', signal.reason.name); // "AbortError"
}, { once: true });
controller.abort();Designing the API: An Optional signal in the Options Object
Built-in APIs such as fetch and addEventListener accept a signal as a signal property of an options object. Follow the same convention. Destructure the options with a default of {} so that callers who don't need cancellation can leave the argument out.
function startJob(name, { signal } = {}) {
console.log(`${name} started`);
signal?.addEventListener('abort', () => {
console.log(`${name} stopped:`, signal.reason.name);
}, { once: true });
}
startJob('no-signal job');
const controller = new AbortController();
startJob('report', { signal: controller.signal });
controller.abort(); // "report stopped: AbortError"The optional chaining (signal?.) keeps the function working when no signal is passed.
Exercise
Why should your function receive an AbortSignal rather than the AbortController, and what does signal.reason contain after controller.abort() is called with no argument?
Show answer
The signal lets the function observe cancellation without being able to trigger it, so only the caller decides when to cancel. After abort() with no argument, signal.reason is a DOMException whose name is "AbortError".