Cooperative cancellation
Pass a signal to a promise-based API so a controller can cancel the operation.
Node.js · Class
AbortSignal is an EventTarget-based cancellation signal for selected promise APIs. It can be created in an aborted, timed, or composed form and exposes cancellation state and reason.
AbortSignal is an EventTarget-based cancellation signal used by selected promise APIs. An AbortController triggers it, while static factories can create an already-aborted signal, a timed signal, or a signal composed from several signals.
class AbortSignal extends EventTarget
AbortSignal.abort([reason])
AbortSignal.timeout(delay)
AbortSignal.any(signals)| Name | Type | Description |
|---|---|---|
reason | any | Optional value attached to a signal created by AbortSignal.abort(). |
delay | number | Milliseconds before the returned signal aborts. |
signals | AbortSignal[] | Signals used to compose a signal that follows the first one to abort. |
AbortSignal instances from the static factory methods; the class exposes aborted, onabort, and reason properties.
const controller = new AbortController();
const signal = AbortSignal.any([
controller.signal,
AbortSignal.timeout(1000),
]);
signal.addEventListener('abort', () => {
console.log('aborted:', signal.reason);
}, { once: true });
setTimeout(() => controller.abort(new Error('cancelled')), 100);Combines caller cancellation with a one-second deadline and reports the reason when the resulting signal aborts.
Pass a signal to a promise-based API so a controller can cancel the operation.
Create a deadline that automatically cancels work after a fixed duration.
Combine user cancellation with a timeout or another cancellation source.
AbortSignal represents cancellation state and dispatches an abort event when its associated controller is aborted. APIs that accept a signal can observe that event or inspect aborted and reason.
Follow-up: How can a deadline be added without manually managing a timer? Use AbortSignal.timeout(delay), which returns a signal aborted after the specified number of milliseconds.
AbortSignal.abort(reason) creates a signal that is already aborted, optionally carrying reason. AbortSignal.timeout(delay) creates one that aborts after delay milliseconds.
Follow-up: What if cancellation may come from either a caller or a deadline? Compose both with AbortSignal.any([callerSignal, timeoutSignal]).
AbortSignal.any(signals) returns a signal that aborts when any supplied signal aborts. Its reason is taken from the signal that caused the composition to abort.
Follow-up: How should consumers handle the composed signal's reason? Inspect signal.reason after abort and account for whichever cancellation source won.
AbortControllerEventTargetAbortSignal.abort()AbortSignal.timeout()AbortSignal.any()