← Back to Node.js, page 6

nodejs-0118 · Medium mid

An EventEmitter has one async listener between two normal ones. ```js const EventEmitter = require('node:events'); const emitter = new EventEmitter(); emitter.on('job', () => console.log('listener 1')); emitter.on('job', async () => { console.log('listener 2 start'); await null; console.log('listener 2 end'); }); emitter.on('job', () => console.log('listener 3')); console.log('before emit'); emitter.emit('job'); console.log('after emit'); ``` What does it print, and why?

emit calls listeners synchronously in registration order and does not wait for promises. The async listener runs until its first await, then emit continues with listener 3 and returns. The rest of the async listener runs later as a microtask. If an async listener rejects, nobody catches it, so it becomes an unhandled rejection unless captureRejections is turned on.

Full answer

EventEmitter is synchronous. emit() loops over the listeners and calls each one. It ignores return values, including promises.

Output of the puzzle: before emit, listener 1, listener 2 start, listener 3, after emit, listener 2 end.

  • The async listener starts running at once, up to await null.
  • The await schedules the rest as a microtask, and the async function returns a pending promise to emit, which ignores it.
  • listener 3 runs, emit returns, and the main code prints after emit.
  • When the main code finishes, the microtask runs: listener 2 end.

The error problem:

  • A throw inside a normal listener propagates out of emit() into the caller, and later listeners do not run.
  • A rejection inside an async listener does not reach the caller. It becomes an unhandledRejection, which crashes modern Node by default.
  • Option: new EventEmitter({ captureRejections: true }) (or events.captureRejections = true). A rejected promise from a listener is then sent to the 'error' event, or to a Symbol.for('nodejs.rejection') method if you define one. Always add an 'error' listener.
  • Option: wrap async listeners in your own try/catch and log the error.

Design rules: never rely on emit() waiting for async work. If the caller must wait, use a different pattern, such as a method that returns Promise.all of the handlers, or events.once for one event.

javascript
const EventEmitter = require('node:events');
const { setTimeout: sleep } = require('node:timers/promises');

async function main() {
  const emitter = new EventEmitter();
  emitter.on('job', () => console.log('listener 1'));
  emitter.on('job', async () => {
    console.log('listener 2 start');
    await null;
    console.log('listener 2 end');
  });
  emitter.on('job', () => console.log('listener 3'));

  console.log('before emit');
  emitter.emit('job');
  console.log('after emit');
  await sleep(10);

  // An async listener that fails, without protection.
  process.once('unhandledRejection', (err) => console.log('unhandled rejection:', err.message));
  const plain = new EventEmitter();
  plain.on('x', async () => { throw new Error('async failure'); });
  plain.emit('x');
  await sleep(10);

  // The same, with captureRejections.
  const safe = new EventEmitter({ captureRejections: true });
  safe.on('error', (err) => console.log("'error' event received:", err.message));
  safe.on('x', async () => { throw new Error('async failure'); });
  safe.emit('x');
  await sleep(10);
}
main();

The first block is the puzzle. The next two blocks show a failing async listener with and without captureRejections. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): before emit listener 1 listener 2 start listener 3 after emit listener 2 end unhandled rejection: async failure 'error' event received: async failure

Key points

  • emit runs listeners synchronously and ignores returned promises.
  • The async listener resumes after emit returns.
  • A rejection in an async listener becomes an unhandled rejection.
  • captureRejections routes it to the 'error' event.
  • Do not rely on emit() to wait for async work.

Common mistakes

  • Expecting emit() to wait for an async listener.
  • Letting an async listener throw with no protection.
  • Using captureRejections without an 'error' listener.
  • Assuming a throw in a listener is caught by emit.
  • Using the order of async listener completion as logic.

Follow-ups

  • How does events.once let you wait for an event?
  • What happens to the remaining listeners when one of them throws?
  • How would you make emit return a promise that waits for all handlers?

Tips

  • Say 'emit is synchronous' first.
  • Trace the order, then add the error case.
  • Mention captureRejections by name.