Sub topic 1
Why Your Async Functions Should Be Cancellable
An asynchronous function begins work that finishes later. That work might be a network request, a timer, a file read, or a loop that polls a server. Often the reason for doing the work goes away before it finishes. The user types another character, closes a dialog, or leaves the page. If your function gives the caller no way to stop it, the work keeps running, holds on to resources, and may deliver a result that is now wrong.
This chapter explains what cancellation means and what goes wrong without it. It also explains why JavaScript settled on one standard mechanism, AbortSignal, instead of letting each library invent its own.
Prerequisites
This tutorial assumes you can already work with the following:
- JavaScript functions, closures, and destructuring
- Promises and
async/await try/catcherror handling- Basic event listeners with
addEventListener setTimeoutandfetch
The examples run in any modern browser and in Node.js 18 or later. Code that touches the DOM needs a browser.
What "Cancellation" Actually Means
Cancellation is a message from the caller to the function it called: "I no longer need the result." A function that supports cancellation responds in three ways:
- It stops doing work. It sends no more requests, starts no more loop iterations, and schedules no more timers.
- It releases resources. It clears timers, removes listeners, and closes connections or file handles.
- It settles its promise, usually by rejecting with an error that says the work was cancelled. The caller is never left waiting on a promise that will never resolve.
A promise cannot do any of this by itself. A promise represents the result of an operation, not the operation itself. It has no cancel() method, and other code holding the same promise cannot reach back and stop whatever produces the value. To stop the work, the function that started it must accept a cancellation request and act on it. Designing that part of the function is what this tutorial teaches.
Problem One: Stale Results Overwrite Fresh Ones
Search-as-you-type is the classic case. Each keystroke starts a request. Responses can come back in any order, so an older, slower request may finish after a newer one and overwrite the correct result.
The following script simulates this. The search for "a" is slow and the search for "ab" is fast:
function fakeSearch(query) {
const ms = query.length === 1 ? 300 : 100;
return new Promise((resolve) => {
setTimeout(() => resolve(`results for "${query}"`), ms);
});
}
let shown = null;
async function onInput(query) {
const result = await fakeSearch(query);
shown = result;
console.log('showing:', shown);
}
onInput('a');
onInput('ab');
// Output:
// showing: results for "ab"
// showing: results for "a" <- the stale result winsThe screen ends up showing results for "a" even though the user typed "ab". The slow request should have been cancelled when the second keystroke arrived.
Problem Two: Work That Outlives Its Purpose
The second problem is waste and leaks. Suppose a component starts polling a status endpoint every few seconds and the user then closes that component. If the polling loop cannot be stopped, it keeps sending requests forever. It also keeps a reference to its callback, which keeps everything the callback closes over alive, so the garbage collector cannot reclaim it.
On a server, the same thing happens when a client disconnects mid-request. The handler keeps querying the database and calling other services to build a response nobody will read. Under load, that wasted work adds up.
The table below lists common situations and what non-cancellable code costs in each one.
| Situation | What should stop | Cost if it keeps running |
|---|---|---|
| User types another search term | The previous request | Stale results, wasted bandwidth |
| User closes a dialog or leaves a route | Polling, timers, subscriptions | Memory leaks, background traffic |
| Client disconnects from a server | Database queries, downstream calls | CPU and connection pool pressure |
| Operation exceeds its time budget | Whatever is still in flight | Hung requests, cascading slowdowns |
| Batch job is stopped by an operator | Remaining loop iterations | Unwanted side effects, wasted time |
The Ad Hoc Fix and Why It Falls Short
Before a standard existed, developers often added a "stopped" flag and returned a function that set it:
function startPolling(check, intervalMs) {
let stopped = false;
async function loop() {
while (!stopped) {
await check();
await new Promise((resolve) => setTimeout(resolve, intervalMs));
}
}
loop();
return () => {
stopped = true;
};
}
const stop = startPolling(async () => console.log('checking...'), 1000);
setTimeout(stop, 3500);This works for this one function, but it has real limits:
- It cannot interrupt work already in progress. Setting the flag has no effect on the current
setTimeoutor on afetchalready running insidecheck(). The loop only notices the flag at its next check. - The promise never says it was cancelled.
loop()simply exits. Code awaiting a result from a function like this cannot tell "finished" from "stopped." - Every function invents its own API. One library returns a
stopfunction, another has a.cancel()method, a third takes a token object. Callers must learn each one, and none of them can be passed to the others. - It does not compose. If your function calls
fetchand another helper, you have to translate your flag into each callee's cancellation style by hand, if they support cancellation at all.
The Standard Answer: AbortController and AbortSignal
The web platform and Node.js share one cancellation mechanism. An AbortController is the object the caller keeps, and its abort() method triggers cancellation. Its signal property is an AbortSignal, a read-only object the caller passes to the work. The work checks the signal's state and listens for its abort event.
Splitting the two roles matters. The caller holds the power to cancel. The function only receives the signal, so it can observe cancellation but cannot trigger it for anyone else.
Many built-in APIs already accept a signal through an options object, for example:
fetch(url, { signal })in browsers and Node.jsaddEventListener(type, listener, { signal })- Node.js
fs.promises.readFile(path, { signal }) - Node.js
setTimeoutfromtimers/promises,events.once,stream.pipeline, andchild_process.spawn
When your own functions follow the same convention, callers get one consistent way to cancel everything. A single signal can be passed down through your code into fetch and the other built-ins, and one abort() call stops the whole chain. Later chapters build exactly this.
What a Well-Behaved Cancellable Function Promises
The rest of this tutorial works toward functions that meet these expectations, the same ones built-in APIs meet:
- They accept an optional
signalin an options object and work normally without one. - They reject right away if the signal is already aborted when they are called.
- They reject promptly with
signal.reasonwhen an abort happens mid-operation. - They clear timers and remove listeners on every path: success, failure, and abort.
- They forward the signal to every cancellable operation they start.
- They let callers tell cancellation, timeouts, and real errors apart.
Exercise
In the search-as-you-type example, a teammate suggests fixing the bug by checking whether the query is still the latest one before assigning shown, without cancelling anything. Which problem does this fix, and which problem from the chapter does it leave unsolved?
Show answer
It fixes the stale-result bug, because outdated results are discarded instead of displayed. It does not stop the work: the slow request still runs to completion, using network and server resources and keeping its callback alive until it settles. Cancellation solves both problems, because it aborts the outdated request.
Exercise
Name two concrete limitations of the "stopped flag" pattern in startPolling compared with passing an AbortSignal.
Show answer
Any two of: it cannot interrupt a timer or fetch that is already in progress, so stopping waits for the next loop check; the function's promise exits silently instead of rejecting, so callers cannot tell a stop from completion; its stop API is specific to this function and cannot be passed to fetch or other APIs; it does not compose across nested calls without manual translation.