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.
Code
// 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: AbortErrorHow 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:eventsis 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
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Does this require external packages?
- No — `node:events` is a Node.js built-in module; nothing to install.
Report a problem with this exampleOpens a pre-filled issue on GitHub.