← Back to Node.js, page 2

nodejs-0033 · Hard senior

What advanced EventEmitter features should a senior developer know: events.once, events.on, prependListener and AbortSignal?

events.once(emitter, name) returns a promise for the next event and rejects if 'error' fires first. events.on(emitter, name) is an async iterator over events and can be cancelled with an AbortSignal. prependListener adds a listener before the existing ones. These let event code use async/await cleanly.

Full answer

Classic listeners work well for continuous events, but they are awkward when you want "wait for the next event and then continue". The events module has helpers for that:

  • events.once(emitter, 'ready') returns a promise that resolves with an array of the event arguments. If the emitter emits 'error' first, the promise rejects with it, and the listeners are removed in both cases. Pass { signal } to cancel the wait.
  • events.on(emitter, 'tick') returns an async iterator. Use for await to process events one by one. Events that arrive while your loop body is busy are queued. Break out of the loop or abort the signal to stop, which removes the listeners.
  • emitter.prependListener(name, fn) and prependOnceListener put a listener at the front of the list. Useful for a validation or logging step that must run first.
  • events.errorMonitor: a symbol you can listen to for errors without changing the normal rule that an unhandled 'error' still throws. Good for metrics.
  • new EventEmitter({ captureRejections: true }): if an async listener rejects, the rejection is sent to the 'error' event instead of becoming an unhandled rejection.
  • events.getEventListeners and events.setMaxListeners work with EventTarget too, since the browser style EventTarget also exists in Node.

A caution: emit is still synchronous. An async listener returns a promise that emit ignores, so errors inside it are not seen unless captureRejections is on.

javascript
const { EventEmitter, once, on } = require('node:events');

async function main() {
  const feed = new EventEmitter();

  // prependListener changes the order.
  feed.on('result', () => console.log('listener 2 (added with on)'));
  feed.prependListener('result', () => console.log('listener 1 (prepended)'));
  feed.emit('result');

  // once: wait for the next event with await.
  setTimeout(() => feed.emit('ready', 'exam hall open', 42), 5);
  const [message, seats] = await once(feed, 'ready');
  console.log('once resolved with:', message, seats);

  // once rejects when 'error' is emitted first.
  setTimeout(() => feed.emit('error', new Error('hall closed')), 5);
  try {
    await once(feed, 'ready');
  } catch (err) {
    console.log('once rejected with:', err.message);
  }

  // on: async iteration with cancellation.
  const controller = new AbortController();
  setTimeout(() => {
    feed.emit('mark', 'Asha', 78);
    feed.emit('mark', 'Ravi', 91);
    setTimeout(() => controller.abort(), 5);
  }, 5);
  try {
    for await (const [name, marks] of on(feed, 'mark', { signal: controller.signal })) {
      console.log('on received:', name, marks);
    }
  } catch (err) {
    console.log('loop ended by:', err.name);
  }
  console.log('listeners left on "mark":', feed.listenerCount('mark'));
}

main();

The aborted loop ends with AbortError and removes its own listeners. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): listener 1 (prepended) listener 2 (added with on) once resolved with: exam hall open 42 once rejected with: hall closed on received: Asha 78 on received: Ravi 91 loop ended by: AbortError listeners left on "mark": 0

Key points

  • events.once is a promise for the next event, and rejects on 'error'.
  • events.on is an async iterator, cancelled with AbortSignal.
  • prependListener controls the order.
  • captureRejections routes async listener errors to 'error'.

Common mistakes

  • Using async listeners and expecting emit to wait for them.
  • Awaiting events.once after the event has already fired, so it waits forever.
  • Not passing a signal or timeout, so a wait can hang.
  • Forgetting that the result of events.once is an array.

Follow-ups

  • How do you add a timeout to events.once?
  • How does EventTarget differ from EventEmitter?
  • What does errorMonitor give you that an 'error' listener does not?

Tips

  • Start from the problem: 'wait for one event' is awkward with callbacks.
  • Mention cancellation, because it separates careful code from fragile code.
  • Know the one-line difference between sync emit and async listeners.