Async Iteration Over Emitter Events

events.on exposes an EventEmitter as an async iterable; when the passed AbortSignal fires the loop raises AbortError, so consumers can bound how much they read.

JavascriptResilience

Code

javascriptsnippet
25 lines
// events.on turns an EventEmitter into an async iterable; an AbortSignal
// ends the iteration from either side.
import { EventEmitter, on } from 'node:events';

const emitter = new EventEmitter();
const controller = new AbortController();
const seen = [];

const consumer = (async () => {
  try {
    for await (const [level, message] of on(emitter, 'log', { signal: controller.signal })) {
      seen.push(level + ': ' + message);
      if (seen.length === 3) controller.abort();
    }
  } catch (error) {
    seen.push('stopped: ' + error.name);
  }
})();

emitter.emit('log', 'info', 'cache warmed');
emitter.emit('log', 'warn', 'stale entry evicted');
emitter.emit('log', 'info', 'health check passed');

await consumer;
console.log(seen.join(' | '));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

info: cache warmed | warn: stale entry evicted | info: health check passed | stopped: AbortError

How it works

Async Iteration Over Emitter Events comes down to the function consumer.

Repetition is confined to for await (const [level, message] of on(emitter, 'log', { signal: controller.signal })) — the rest of the file is straight-line. Every asynchronous step is awaited, so rejections surface where the call happens. The import names the platform contact area: EventEmitter, on, all from node:events.

What to watch for

  • node:events is a Node.js built-in module — it ships with the runtime, so there is nothing to install.

Putting it to use

The primary signature is const consumer = (async ()

Core lines

for await (const [level, message] of on(emitter, 'log', { signal: controller.signal })) {
  seen.push(level + ': ' + message);
  if (seen.length === 3) controller.abort();
}
const controller = new AbortController();
await consumer;

Interactive Tools for This Topic

FAQ

Does this require external packages?
No — `node:events` is a Node.js built-in module; nothing to install.