events.addAbortListener(signal, listener)


稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

在提供的 signal 上监听一次 abort 事件。

¥Listens once to the abort event on the provided signal.

监听中止信号上的 abort 事件是不安全的,并且可能导致资源泄漏,因为具有该信号的另一个第三方可以调用 e.stopImmediatePropagation()。不幸的是 Node.js 无法改变这一点,因为它违反了 Web 标准。此外,原始 API 很容易忘记删除监听器。

¥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.

此 API 允许在 Node.js API 中安全地使用 AbortSignal,通过监听事件来解决这两个问题,这样 stopImmediatePropagation 就不会阻止监听器运行。

¥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) {
  let disposable;
  try {
    signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
    disposable = addAbortListener(signal, (e) => {
      // Do something when signal is aborted.
    });
  } finally {
    disposable?.[Symbol.dispose]();
  }
}import { addAbortListener } from 'node:events';

function example(signal) {
  let disposable;
  try {
    signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
    disposable = addAbortListener(signal, (e) => {
      // Do something when signal is aborted.
    });
  } finally {
    disposable?.[Symbol.dispose]();
  }
}