Timeout-driven cancellation
Cancel a fetch or other supported asynchronous operation when a deadline expires.
Node.js · Class
AbortController signals cancellation to selected Promise-based APIs. Pass its signal to an operation and call abort() to trigger cancellation notification.
AbortController coordinates cancellation for supported Promise-based APIs. Create one, give its signal to an operation, and call abort() to emit the abort event; an optional reason becomes available through the signal.
new AbortController();
abortController.abort([reason])| Name | Type | Description |
|---|---|---|
reason | any | Optional value recorded as the signal's reason and retrievable from AbortSignal.reason. |
abort(reason) returns undefined; the controller exposes its associated AbortSignal through the signal property.
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(new Error('Timed out')), 100);
try {
await fetch('https://nodejs.org', { signal: controller.signal });
console.log('Request completed');
} catch (error) {
if (controller.signal.aborted) console.log('Request cancelled');
else throw error;
} finally {
clearTimeout(timeout);
}Creates a controller, passes its signal to fetch, and aborts the request after 100 milliseconds.
Cancel a fetch or other supported asynchronous operation when a deadline expires.
Let a user, request handler, or shutdown routine stop an in-flight operation.
Propagate a cancellation reason to code observing the operation.
AbortController is a utility class for signaling cancellation to selected Promise-based APIs. Pass its signal to the API, then call abort() when cancellation is needed.
Follow-up: What does abort() do to the signal? It causes the controller's signal to emit the abort event and marks the signal as aborted.
Calling abort(reason) triggers the controller's signal and optionally records the supplied value as the signal's reason. The reason can be any value.
Follow-up: Can the same controller be reset? No; its associated signal can trigger the abort event only once, so create a new controller for another operation.
The signal is the object observers and supported APIs use to learn that cancellation was requested. It emits an 'abort' event when its controller's abort() method is called.
Follow-up: How should an event listener be registered when it only needs to run once? Use an event listener option with once: true, as shown in the documentation example.
AbortSignalAbortSignal.abort()AbortSignal.timeout()