events.EventEmitterAsyncResource 类继承 EventEmitter 类


为需要手动异步跟踪的 EventEmitter 集成 EventEmitter<AsyncResource>。 具体来说,events.EventEmitterAsyncResource 实例触发的所有事件都将在其异步上下文中运行。

const { EventEmitterAsyncResource } = require('node:events');
const { notStrictEqual, strictEqual } = require('node:assert');
const { executionAsyncId } = require('node:async_hooks');

// 异步跟踪工具会将其识别为 'Q'。
const ee1 = new EventEmitterAsyncResource({ name: 'Q' });

// 'foo' 监听器将在 EventEmitter 异步上下文中运行。
ee1.on('foo', () => {
  strictEqual(executionAsyncId(), ee1.asyncId);
  strictEqual(triggerAsyncId(), ee1.triggerAsyncId);
});

const ee2 = new EventEmitter();

// 普通 EventEmitter 上的 'foo' 监听器不跟踪异步上下文,
// 但是,在与 emit() 相同的异步上下文中运行。
ee2.on('foo', () => {
  notStrictEqual(executionAsyncId(), ee2.asyncId);
  notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId);
});

Promise.resolve().then(() => {
  ee1.emit('foo');
  ee2.emit('foo');
});

EventEmitterAsyncResource 类具有与 EventEmitterAsyncResource 本身相同的方法和选项。

Integrates EventEmitter with <AsyncResource> for EventEmitters that require manual async tracking. Specifically, all events emitted by instances of events.EventEmitterAsyncResource will run within its async context.

const { EventEmitterAsyncResource } = require('node:events');
const { notStrictEqual, strictEqual } = require('node:assert');
const { executionAsyncId } = require('node:async_hooks');

// Async tracking tooling will identify this as 'Q'.
const ee1 = new EventEmitterAsyncResource({ name: 'Q' });

// 'foo' listeners will run in the EventEmitters async context.
ee1.on('foo', () => {
  strictEqual(executionAsyncId(), ee1.asyncId);
  strictEqual(triggerAsyncId(), ee1.triggerAsyncId);
});

const ee2 = new EventEmitter();

// 'foo' listeners on ordinary EventEmitters that do not track async
// context, however, run in the same async context as the emit().
ee2.on('foo', () => {
  notStrictEqual(executionAsyncId(), ee2.asyncId);
  notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId);
});

Promise.resolve().then(() => {
  ee1.emit('foo');
  ee2.emit('foo');
});

The EventEmitterAsyncResource class has the same methods and takes the same options as EventEmitter and AsyncResource themselves.