Full answer
Promises cannot be cancelled, so cancellation needs a separate signal. The platform provides AbortController for this. The controller owns a signal property, which is an AbortSignal. The signal is handed to the work, and the controller keeps abort().
Calling controller.abort(reason) sets signal.aborted to true, stores signal.reason, and fires an abort event once. APIs that accept { signal }, such as fetch, stop and reject their promise with the reason. The default reason is a DOMException named AbortError.
To make your own function cancellable, check the signal at the start with signal.throwIfAborted(), add an abort listener that cancels the timer or request and rejects the promise, and remove the listener when the work finishes normally so it does not leak.
AbortSignal.timeout(ms) creates a signal that aborts itself after a delay, with a reason named TimeoutError. AbortSignal.any([a, b]) aborts when any of the given signals does, which combines a user cancel button with a timeout.
Uses include cancelling a search request when the user types again (avoiding out-of-order responses), cancelling work when a component is removed, and request timeouts. Cancelling does not undo side effects that already reached the server, so server operations should be idempotent or confirmed.
One signal can cancel many operations, and a signal that has already aborted stays aborted.
function delay(ms, { signal } = {}) {
return new Promise((resolve, reject) => {
signal?.throwIfAborted();
const timer = setTimeout(() => {
signal?.removeEventListener('abort', onAbort);
resolve(`finished after ${ms} ms`);
}, ms);
function onAbort() {
clearTimeout(timer);
reject(signal.reason);
}
signal?.addEventListener('abort', onAbort, { once: true });
});
}
(async () => {
console.log(await delay(10));
const controller = new AbortController();
const pending = delay(200, { signal: controller.signal });
setTimeout(() => controller.abort(), 20);
try {
await pending;
} catch (error) {
console.log('manual abort:', error.name, controller.signal.aborted);
}
try {
await delay(200, { signal: AbortSignal.timeout(20) });
} catch (error) {
console.log('timeout:', error.name);
}
const userCancel = new AbortController();
const combined = AbortSignal.any([userCancel.signal, AbortSignal.timeout(500)]);
userCancel.abort(new Error('user pressed cancel'));
try {
await delay(100, { signal: combined });
} catch (error) {
console.log('combined:', error.message);
}
const reused = new AbortController();
reused.abort();
try {
await delay(10, { signal: reused.signal });
} catch (error) {
console.log('already aborted:', error.name);
}
})();Run with Node.js v24.22.1 as js-41.js; two runs gave identical output. Output: finished after 10 ms manual abort: AbortError true timeout: TimeoutError combined: user pressed cancel already aborted: AbortError
Key points
- Promises cannot cancel; a signal carries the cancel request.
- abort() sets aborted, stores reason, and fires the abort event once.
- Cancellable APIs reject with the reason, AbortError by default.
- Custom async functions should check, listen, clean up, and remove their listener.
- AbortSignal.timeout and AbortSignal.any cover timeouts and combined sources.
Common mistakes
- Believing abort() undoes work the server already completed.
- Forgetting to remove the abort listener after normal completion.
- Catching the AbortError and treating it as a real failure with an error message to the user.
- Reusing one controller after abort and expecting a new request to run.
Follow-ups
- How would you avoid showing results from an old search request when the user types quickly?
- How do you pass a signal through several layers of async functions?
- What does fetch reject with when the signal times out compared with a manual abort?
Tips
- State that promises cannot be cancelled before you show the solution.
- Show the cleanup of timers and listeners; it is the difference between a demo and production code.
- Mention one real case such as a search box, and the race condition it prevents.