CodePark/ questions / EventEmitter
START PRACTICINGPRACTICE
Backend question · Node.js › EventEmitter

What happens if an async function is used as an EventEmitter listener and it rejects? How can you handle it?

The rejection is unhandled, and since Node 15 it crashes the process by default. The emitter's error event does not fire.

Why? emit calls the listener and ignores its return value. An async function returns a promise, so nobody awaits that promise. If the promise rejects, no code handles the rejection.

You have two options:

  • Catch errors inside the listener with try/catch.
  • Create the emitter with new EventEmitter({ captureRejections: true }). You can also turn this on for all emitters with EventEmitter.captureRejections = true.

With captureRejections, Node adds a rejection handler to the promise for you. It sends the error to the error event. If the emitter has a Symbol.for('nodejs.rejection') method, Node sends the error to that method instead.

Related: events.once(emitter, name) returns a promise for the next event. The promise rejects if error is emitted first. This is useful when you want to await a single event.

  • emit ignores the promise that the listener returns.
  • Rejections become unhandled and can crash the process.
  • Wrap the body of each async listener in try/catch.
  • captureRejections: true sends rejections to the error event.
  • events.once awaits one event and rejects if error comes first.