AbortSignal and timeouts
suggest changeModern Node.js provides first-class support for canceling asynchronous operations using the standard AbortController and AbortSignal APIs. Instead of relying on manual timer cleanup or third-party cancellation tokens, Node.js core modules and global web APIs accept an AbortSignal to cancel HTTP requests, file reads, child processes, and timers.
Timeouts with AbortSignal.timeout()
In Node.js 17.3 and later, AbortSignal.timeout(milliseconds) creates an AbortSignal that automatically aborts after the specified duration.
Canceling fetch Requests
Pass the signal to fetch to prevent network requests from hanging indefinitely:
try {
// Automatically cancel if the request takes longer than 3 seconds
const response = await fetch('https://api.example.com/data', {
signal: AbortSignal.timeout(3000),
});
const data = await response.json();
console.log('Received data:', data);
} catch (err) {
if (err.name === 'TimeoutError') {
console.error('Request timed out after 3000ms');
} else {
console.error('Network or fetch error:', err);
}
}
Manual Cancellation with AbortController
Use AbortController when cancellation is triggered by external events (such as user action, application shutdown, or task completion):
const controller = new AbortController();
const { signal } = controller;
// Trigger cancellation after 1 second
setTimeout(() => {
controller.abort(new Error('User clicked cancel'));
}, 1000);
try {
const response = await fetch('https://httpbin.org/delay/5', { signal });
console.log('Finished');
} catch (err) {
// fetch rejects with the abort reason itself (here our Error),
// so check the signal rather than err.name
if (signal.aborted) {
console.log('Operation aborted:', signal.reason.message);
} else {
throw err;
}
}
Using AbortSignal with Node.js Core Modules
Many Node.js standard library APIs natively accept a { signal } option:
1. File System Operations (node:fs/promises)
import { readFile } from 'node:fs/promises';
try {
const content = await readFile('large-file.bin', {
signal: AbortSignal.timeout(500),
});
console.log(`Read ${content.length} bytes`);
} catch (err) {
if (err.name === 'AbortError') {
console.error('File read canceled before completion');
}
}
2. Timers Promise API (node:timers/promises)
import { setTimeout } from 'node:timers/promises';
const controller = new AbortController();
setTimeout(200).then(() => controller.abort());
try {
// Waits up to 1000ms unless aborted
await setTimeout(1000, 'done', { signal: controller.signal });
} catch (err) {
if (err.name === 'AbortError') {
console.log('Timer was interrupted early');
}
}
3. Child Processes (node:child_process)
import { exec } from 'node:child_process';
import { promisify } from 'node:util';
const execPromise = promisify(exec);
try {
// Kills child process if it runs longer than 2 seconds
const { stdout } = await execPromise('sleep 10', {
signal: AbortSignal.timeout(2000),
});
} catch (err) {
if (err.name === 'AbortError') {
console.log('Command exceeded execution time limit');
}
}
Combining Signals with AbortSignal.any()
Node.js 20 introduced AbortSignal.any(), allowing you to combine multiple signals into one. The composite signal aborts as soon as any input signal aborts (for example, combining a manual user cancel with an absolute timeout):
const userCancelController = new AbortController();
const timeoutSignal = AbortSignal.timeout(5000);
// Aborts if user cancels OR if 5000ms elapses
const combinedSignal = AbortSignal.any([
userCancelController.signal,
timeoutSignal,
]);
try {
const res = await fetch('https://example.com', { signal: combinedSignal });
} catch (err) {
if (combinedSignal.aborted) {
console.log('Aborted due to:', combinedSignal.reason);
}
}
Custom Cancellable Functions
You can make your own asynchronous functions cancellable by listening to the abort event:
function waitForEvent(emitter, eventName, { signal } = {}) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
return reject(signal.reason);
}
const onEvent = (...args) => {
cleanup();
resolve(args);
};
const onAbort = () => {
cleanup();
reject(signal.reason);
};
const cleanup = () => {
emitter.off(eventName, onEvent);
signal?.removeEventListener('abort', onAbort);
};
emitter.once(eventName, onEvent);
signal?.addEventListener('abort', onAbort, { once: true });
});
}