Categories
Node.js Quick Tips Quick Tips

Avoid boilerplate code when handling abort signals

< 1 min read

This blog post is part of What’s new in Node.js core? March 2022 edition.

The AbortSignal API in Node.js has a new method: throwIfAborted()

If the abort signal has been triggered, it’ll throw the value of the reason property. This saves writing boilerplate checking and handling code.

Contributed by James M Snell

Example

const ac = new AbortController();

ac.abort();

ac.signal.throwIfAborted();

// > DOMException [AbortError]: This operation was aborted

Support in Node.js

Also supported by Deno, as well as some web browsers.

When can you use it in production?

Likely to be backported to v16 (Active LTS), but not yet confirmed.

Will be in v18 — initial release 19 Apr 2022, Active LTS starts 25 Oct 2022.

Leave a Reply

Your email address will not be published. Required fields are marked *