M
events.addAbortListener
History
Added in: v20.5.0, v18.18.0
v20.5.0, v18.18.0
Introduced in: v0.10.0
v0.10.0
Change stability index for this feature from Experimental to Stable.
v24.0.0, v22.16.0
events.addAbortListener(signal, listener): Disposable
Attributes
signal:
AbortSignallistener:
Function | EventListenerReturns:
DisposableA Disposable that removes the
abort listener.Listens once to the abort event on the provided signal.
Listening to the abort event on abort signals is unsafe and may
lead to resource leaks since another third party with the signal can
call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
this since it would violate the web standard. Additionally, the original
API makes it easy to forget to remove listeners.
This API allows safely using AbortSignals in Node.js APIs by solving these
two issues by listening to the event such that stopImmediatePropagation does
not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
const { addAbortListener } = require('node:events'); function example(signal) { signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); // addAbortListener() returns a disposable, so the `using` keyword ensures // the abort listener is automatically removed when this scope exits. using _ = addAbortListener(signal, (e) => { // Do something when signal is aborted. }); }
import { addAbortListener } from 'node:events'; function example(signal) { signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); // addAbortListener() returns a disposable, so the `using` keyword ensures // the abort listener is automatically removed when this scope exits. using _ = addAbortListener(signal, (e) => { // Do something when signal is aborted. }); }