Sub topic 1
Why Your Async Functions Should Be Cancellable
Asynchronous work often outlives the reason it started. A user types a search query and then changes it. Someone opens a page and leaves before its data loads. A component unmounts while a timer is still pending. If your functions can't be stopped, the work keeps going after nobody needs it, and its results can arrive at the wrong moment.
This chapter explains the problem that cancellation solves. Later chapters build the solution step by step with AbortController and AbortSignal.
Prerequisites
This tutorial assumes you are comfortable with:
- JavaScript functions, closures, and destructuring
- Promises and
async/await try/catcherror handling- Basic event listeners with
addEventListener setTimeoutandfetch
The cost of work nobody can stop
Here is a delay helper that most codebases contain in some form:
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function showGreeting() {
await delay(3000);
console.log('Greeting shown');
}
showGreeting();
// Even if the user leaves after one second, the timer keeps running.
// Three seconds later, "Greeting shown" is still logged.Once showGreeting() is called, the caller has no way to stop it. That causes these problems:
| Problem | What happens |
|---|---|
| Wasted resources | Timers, network requests, and CPU work continue after their results are no longer needed. |
| Stale results | An old response arrives after a newer one and overwrites fresh data. |
| Leaks | Listeners and timers keep closures, and the objects those closures reference, alive in memory. |
| Errors after teardown | Code updates UI or state that has already been destroyed. |
A race you have probably shipped
Search-as-you-type is a common case. Each keystroke starts a request, and responses can come back in any order.
If the app could cancel request A when the user typed "cat", the stale response would never be displayed.
Why a standard mechanism matters
You could add an isCancelled flag or a custom cancel() method to each function. Every hand-rolled scheme looks a little different, though, and none of them work with the platform. fetch, addEventListener, Node.js streams, and many libraries already accept one standard object, the AbortSignal. If your functions accept the same object, a caller can cancel a whole chain of work with one call, from your helper down to the network request.
What a cancellable function must do
A well-behaved cancellable function:
- Lets the caller pass in a cancellation signal.
- Refuses to start if the signal is already aborted.
- Stops its work when the signal aborts mid-flight.
- Cleans up timers and listeners whether it was cancelled or finished normally.
- Rejects with an error the caller can tell apart from a real failure.
Exercise
In the showGreeting() example, list two resources or side effects that continue after the user leaves the page, and explain why adding an if (userLeft) return; check after await delay(3000) only partly fixes the problem.
Show answer
The pending setTimeout timer keeps running, and the closure holding showGreeting's state stays in memory until it fires. The log line, standing in for a UI update, also runs after it is no longer wanted. A userLeft check after the await stops the side effect, but the timer still runs for the full three seconds because nothing clears it. The flag is also a custom scheme that fetch and other APIs can't understand, so it doesn't pass cancellation down to nested work.