'abort' 事件


当调用 abortController.abort() 方法时,则触发 'abort' 事件。 使用单个对象参数调用回调,该对象具有被设置为 'abort'type 属性:

const ac = new AbortController();

// 使用 onabort 属性...
ac.signal.onabort = () => console.log('aborted!');

// 或者 EventTarget API ...
ac.signal.addEventListener('abort', (event) => {
  console.log(event.type);  // 打印 'abort'
}, { once: true });

ac.abort();

AbortSignal 关联的 AbortController 只会触发一次 'abort' 事件。 建议在添加 'abort' 事件监听器之前代码检查 abortSignal.aborted 属性是否为 false

任何绑定到 AbortSignal 的事件监听器都应使用 { once: true } 选项(或者,如果使用 EventEmitter API 绑定监听器,则使用 once() 方法)以确保在处理 'abort' 事件后立即删除事件监听器。 不这样做可能会导致内存泄漏。

The 'abort' event is emitted when the abortController.abort() method is called. The callback is invoked with a single object argument with a single type property set to 'abort':

const ac = new AbortController();

// Use either the onabort property...
ac.signal.onabort = () => console.log('aborted!');

// Or the EventTarget API...
ac.signal.addEventListener('abort', (event) => {
  console.log(event.type);  // Prints 'abort'
}, { once: true });

ac.abort();

The AbortController with which the AbortSignal is associated will only ever trigger the 'abort' event once. We recommended that code check that the abortSignal.aborted attribute is false before adding an 'abort' event listener.

Any event listeners attached to the AbortSignal should use the { once: true } option (or, if using the EventEmitter APIs to attach a listener, use the once() method) to ensure that the event listener is removed as soon as the 'abort' event is handled. Failure to do so may result in memory leaks.