How to Handle Async Cancellation Correctly
Cancel async work cleanly: propagate an abort signal, release resources in finally, and make downstream operations observe the cancellation.
On this page
Introduction
Cancellation is how a caller stops work it no longer needs: the user navigated away, a timeout fired, a newer request superseded an older one. Without cancellation, the work continues to completion, holding resources and possibly applying a result that is no longer wanted. Cancellation is easy to do wrong because it requires cooperation: every layer of an async operation must observe the cancellation and stop, or the outer cancel is just a promise that nobody honors.
This tutorial handles cancellation with an abort signal, releasing resources in finally, propagating the signal to downstream calls, and distinguishing a cancellation from a failure. The examples use AbortController, fetch, and timers, and the reasoning applies to any async runtime with a cancellation mechanism.
Carry a signal through the call chain
A boolean flag is not cancellation: it has to be checked everywhere and nothing fires it. An abort signal carries an event and a status, and passing it into the operation lets the operation subscribe or hand it to a fetch, which rejects when the signal fires. The signal is the single thing that says stop, and it reaches the deep calls without a custom flag at each level.
Pass the signal as part of the context the operation receives, so every async call in the chain has it. A fetch takes a signal and rejects with an abort error; a database driver may accept one; a child task can be tied to it. Where a dependency does not accept a signal, check signal.aborted before and after it and throw a cancellation error if set, so the cancellation still takes effect at that boundary.
async function loadWithSignal(url, signal) {
if (signal.aborted) throw new Error('cancelled');
const res = await fetch(url, { signal }); // fetch rejects on abort
if (signal.aborted) throw new Error('cancelled');
return res.json();
}
const controller = new AbortController();
loadWithSignal('/data', controller.signal).catch((e) => {
if (e.name === 'AbortError' || e.message === 'cancelled') return; // expected cancel
throw e; // a real error
});
controller.abort(); // cancel in flight
Release resources in finally
Cancellation unwinds the operation but does not run cleanup unless you write it. Place the release of timers, sockets, locks, and file handles in a finally block so the cleanup runs whether the operation completes, fails, or is cancelled. Without it, a cancelled operation leaks the resources it held, and under many cancels the leak accumulates.
For a lock acquired during the operation, release it in finally so a cancelled holder does not keep the lock. For a timer set for a timeout, clear it in finally so it does not fire after the operation is gone. For a stream, destroy it in finally. The rule is that every resource acquired in the operation is released in a finally, because the cancellation path is a path that skips the normal end of the function.
async function withResources(signal) {
const timer = setTimeout(() => {}, 60000); // would fire later without cleanup
const lock = await acquireLock('key');
try {
return await doWork(signal);
} finally {
clearTimeout(timer); // released on success, failure, or cancellation
await lock.release();
}
}
Propagate to child tasks and downstream
Cancelling one operation should cancel the work it started. If the operation spawned child tasks or made downstream calls, each needs the signal, so the whole subtree stops together. Tie child tasks to the parent’s signal so a parent cancel aborts them, and pass the signal to the downstream calls so their requests abort too. A cancellation that stops only the outermost promise leaves the inner work running.
For a fan-out, create a signal that aborts when any child fails or when the parent cancels, so a first failure stops the rest. For a background job, tie it to the signal of the request or the component that owns it, so when the owner goes away, so does the job. The goal is that cancellation of the owner cascades to everything it started.
async function fanOut(urls: string[], signal: AbortSignal) {
const results = [];
for (const url of urls) {
if (signal.aborted) break;
results.push(await fetch(url, { signal }).then((r) => r.json())); // same signal
}
return results;
}
Distinguish cancellation from failure
A cancellation is not a fault: the caller asked for it. Reject with a recognizable cancellation error, and have the immediate caller ignore it when it initiated the cancel. If it is treated as a failure, it triggers retries that immediately re-cancel and alerts for something the caller intended, which floods logs and metrics.
Where a timeout and a caller cancel are both possible, they may produce the same abort error, and the caller usually treats both as ‘stop, do not retry’. If the distinction matters, use a distinct error or reason so the caller can tell a timeout from an explicit cancel. Keep the cancellation error out of the error rate that feeds alerting, since it is an expected control-flow event.
class CancelledError extends Error {
constructor() { super('cancelled'); this.name = 'CancelledError'; }
}
function isCancelled(e) { return e && (e.name === 'AbortError' || e instanceof CancelledError); }
try { await work(signal); }
catch (e) { if (isCancelled(e)) return; metrics.incr('errors'); throw e; }
Test cancellation mid-flight
Start an operation and abort it while it is in flight, then assert the promise rejects with the cancellation error. Assert a resource acquired by the operation, such as a timer or a lock, is released after the cancel, which proves the finally ran. Assert a downstream call was aborted, by a stub that records whether its request aborted. Assert a cancellation is not counted as an error in the metric.
node -e '
const c = new AbortController();
const p = work(c.signal);
setTimeout(() => c.abort(), 10); // cancel mid-flight
p.then(() => console.log("BAD: resolved")).catch((e) => console.log("cancelled:", e.name));
// assert the lock/timer released: check the resource count returns to zero
'
Common pitfalls
Using a boolean flag that nothing triggers, cleanup not in a finally so cancellation leaks resources, forwarding the signal to the outer call but not to downstream or child tasks, treating a cancellation as a failure so it retries and alerts, and a child task not tied to the parent signal so it outlives the parent are the recurring mistakes. A carried signal, finally cleanup, propagation to the whole chain, a distinct cancellation error, and linked child tasks address them.
Conclusion
Cancellation needs cooperation across the whole chain. Carry a signal, release resources in finally, propagate the signal to downstream and child tasks, and treat a cancellation as distinct from a failure. Self-check by aborting an in-flight operation and asserting it rejects as cancelled, releases its resources, and aborts its downstream call. Then a cancel actually stops the work instead of leaving it running in the background.
Sources: MDN: AbortController and AbortSignal, MDN: Fetch with an abort signal, Node.js: AbortController.
FAQ
- How does an AbortSignal cancel an operation?
- The signal carries an aborted flag and an event. The operation checks the signal or passes it to a fetch, which rejects with an abort error when the signal fires. The signal is a standard way to propagate cancellation through a call chain without a custom flag at every level.
- Should cancellation be an error?
- Yes, distinct from a failure: an operation cancelled by the caller is not a fault. Reject with a recognizable cancellation error so callers can ignore it when they initiated the cancel, and so it does not trigger retries or alerts that a real error would.
Report a problem with this articleOpens a pre-filled issue on GitHub.