cac
Options
All
  • Public
  • Public/Protected
  • All
Menu

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.

since

v17.4.0, v16.14.0

Hierarchy

  • EventEmitterAsyncResource

Index

Constructors

Properties

Methods

Constructors

constructor

Properties

Readonly asyncId

asyncId: number

The unique asyncId assigned to the resource.

Readonly asyncResource

The returned AsyncResource object has an additional eventEmitter property that provides a reference to this EventEmitterAsyncResource.

Readonly triggerAsyncId

triggerAsyncId: number

The same triggerAsyncId that is passed to the AsyncResource constructor.

Methods

emitDestroy

  • 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.

    Returns void

Legend

  • Class
  • Constructor
  • Property
  • Method
  • Variable
  • Function
  • Type alias
  • Interface

Generated using TypeDoc