This blog post is part of What’s new in Node.js core? March 2022 edition.
There’s now a built-in way to automatically cancel an async operation after a specified amount of time in Node.js: AbortSignal.timeout()
You could use it to automatically cancel slow HTTP requests, for example.
Contributed by James M Snell
Example A
Create an abort signal which triggers after 1 second.
const signal = AbortSignal.timeout(1000);
signal.addEventListener("abort", () => {
console.log("Signal automatically aborted.");
}, { once: true });
Example B
Create an abort signal which triggers after 200 milliseconds and use it to cancel an HTTP request.
try {
const signal = AbortSignal.timeout(200);
const response = await fetch("https://jsonplaceholder.typicode.com/photos", {
signal,
});
const json = await response.json();
console.log(json);
} catch (error) {
if (error.name === "AbortError") {
console.error("The HTTP request was automatically cancelled.");
} else {
throw error;
}
}
Note: This example uses the experimental Fetch API, introduced behind the
--experimental-fetch
flag in v17.5.0. You don’t need the experimental Fetch API to useAbortSignal.timeout()
.
Support in Node.js
A number of methods in core Node.js modules now accept an AbortSignal
instance via a signal
option (a non-exhaustive list). Quite a few libraries support abort signals too (examples).
Node.js was the first JavaScript runtime to add support for the AbortSignal.timeout()
method.
When can you use it in production?
You can use it now as it was backported to the v16 (Active LTS) release line.
Related links
- Documentation: Node.js
- Node.js release notes: v17.3.0, v16.14.0
- Twitter thread: Posted on Feb 17 2022
If you’re using v16.x, but can’t upgrade to v16.14.0, I wrote an article which shows how to cancel HTTP requests by combining the Abort API and Promise.race()
. I’ll be updating it to include AbortSignal.timeout()
, which is far more convenient.
My talk ‘Improving your applications with AbortController‘ at NodeConf Remote 2021 went in-depth on the Abort API.
4 replies on “Automatically cancel async operations with AbortSignal.timeout()”
Do you have any examples that don’t use the fetch API? I know how they could be wired up, but I don’t know how they could automatically cancel.
i.e. cancel a regular promise, or a setInterval, or a WebSocket request in flight.
Great question! I can see you found the list of Node.js Core APIs which accept abort signals, but I’m going to add more detail on that to this article.
Here’s support for AbortSignal in Node.js core API methods.
https://talk-nodeconf-remote-2021.netlify.app/32?clicks=2
Guessing you spotted this on Twitter — thanks for adding the link!