Usage in Deno
import { EventEmitter } from "node:events"; const { EventEmitterAsyncResource } = EventEmitter;
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.
import { EventEmitterAsyncResource, EventEmitter } from 'node:events'; import { notStrictEqual, strictEqual } from 'node:assert'; import { executionAsyncId, triggerAsyncId } from '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.
EventEmitterAsyncResource(options?: EventEmitterAsyncResourceOptions)
asyncId: number
The unique asyncId assigned to the resource.
The returned AsyncResource object has an additional eventEmitter property
that provides a reference to this EventEmitterAsyncResource.
triggerAsyncId: number
The same triggerAsyncId that is passed to the AsyncResource constructor.
emitDestroy(): void
Call all destroy hooks. This should only ever be called once. An error will
be thrown if it is called more than once. This must be manually called. If
the resource is left to be collected by the GC then the destroy hooks will
never be called.