util.aborted(signal, resource)


稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

  • signal <AbortSignal>

  • resource <Object> 与可中止操作绑定且弱持有的任何非空对象。如果在 signal 中止之前对 resource 进行垃圾收集,则 promise 仍处于待处理状态,允许 Node.js 停止跟踪它。这有助于防止长时间运行或不可取消的操作中的内存泄漏。

    ¥resource <Object> Any non-null object tied to the abortable operation and held weakly. If resource is garbage collected before the signal aborts, the promise remains pending, allowing Node.js to stop tracking it. This helps prevent memory leaks in long-running or non-cancelable operations.

  • 返回:<Promise>

    ¥Returns: <Promise>

监听提供的 signal 上的中止事件,并返回在 signal 中止时解析的 promise。如果提供了 resource,它会弱引用操作的关联对象,因此如果在 signal 中止之前 resource 被垃圾收集,则返回的 promise 将保持待处理状态。这可防止长时间运行或不可取消的操作中发生内存泄漏。

¥Listens to abort event on the provided signal and returns a promise that resolves when the signal is aborted. If resource is provided, it weakly references the operation's associated object, so if resource is garbage collected before the signal aborts, then returned promise shall remain pending. This prevents memory leaks in long-running or non-cancelable operations.

const { aborted } = require('node:util');

// Obtain an object with an abortable signal, like a custom resource or operation.
const dependent = obtainSomethingAbortable();

// Pass `dependent` as the resource, indicating the promise should only resolve
// if `dependent` is still in memory when the signal is aborted.
aborted(dependent.signal, dependent).then(() => {

  // This code runs when `dependent` is aborted.
  console.log('Dependent resource was aborted.');
});

// Simulate an event that triggers the abort.
dependent.on('event', () => {
  dependent.abort(); // This will cause the `aborted` promise to resolve.
});import { aborted } from 'node:util';

// Obtain an object with an abortable signal, like a custom resource or operation.
const dependent = obtainSomethingAbortable();

// Pass `dependent` as the resource, indicating the promise should only resolve
// if `dependent` is still in memory when the signal is aborted.
aborted(dependent.signal, dependent).then(() => {

  // This code runs when `dependent` is aborted.
  console.log('Dependent resource was aborted.');
});

// Simulate an event that triggers the abort.
dependent.on('event', () => {
  dependent.abort(); // This will cause the `aborted` promise to resolve.
});