This blog post is part of the series What’s new in Node.js core?
If you want to cancel an async operation in Node.js, such as an HTTP request, you can now use the built in AbortController
and AbortSignal
classes. They were originally introduced in the Web Platform APIs, which are implemented by web browsers.
Example with node-fetch
Here’s an example of using an AbortSignal
with the node-fetch library:
import fetch from "node-fetch";
import { setTimeout } from "node:timers/promises";
const cancelTimeout = new AbortController();
const cancelRequest = new AbortController();
async function timeout(milliseconds) {
try {
await setTimeout(milliseconds, undefined, { signal: cancelTimeout.signal });
cancelRequest.abort();
} catch (error) {
// Ignore rejections
}
}
async function makeRequest() {
try {
const response = await fetch("http://localhost:3000/", {
signal: cancelRequest.signal,
});
const responseData = await response.json();
return responseData;
} catch (error) {
if (error.name === "AbortError") {
console.error("Request was aborted");
} else {
console.error(error);
}
} finally {
cancelTimeout.abort();
}
}
const result = await Promise.race([timeout(2000), makeRequest()]);
console.log({ result });
Support
Support in Node.js versions:
- Added (Experimental): v15.0.0
- Graduated (Stable): v15.4.0
- Backported (Experimental): v14.17.0
Some methods in core Node.js modules now accept AbortSignal
instances:
http
/https
fs
timers
events
child_process
dgram
See the v14.17.0 release notes for details.
Libraries like node-fetch also accept an AbortSignal
instance as an option.
Related links
- Node.js v14.x AbortController documentation
- Node.js v16.x AbortController documentation
- Using AbortSignal in Node.js. Thanks to James Snell for sharing the
Promise.race
-based timeout pattern in this excellent article.