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 withEventEmitter.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.
emitignores 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: truesends rejections to theerrorevent.events.onceawaits one event and rejects iferrorcomes first.
Read more