util.aborted(signal, resource)
signal<AbortSignal>resource<Object> 任何与可中止操作相关联并被弱引用的非空对象。如果在signal中止之前resource被垃圾回收,Promise 会保持挂起状态,从而允许 Node.js 停止跟踪它。这有助于防止在长时间运行或不可取消的操作中发生内存泄漏。- 返回:<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.
});