events.addAbortListener(signal, listener)


稳定性: 1 - 实验性

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

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

监听中止信号(abort)上的 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]();
  }
}