Reputation: 143
I am writing a Node.js v10 app and I'd like to use await
in an event listener function, so I've made an async
listener function. Based on the code below it seems to work.
But I am curious if there is a hidden downside or something I should be aware of when registering an async
function as an EvenEmitter
listener using the on()
method? Something thing might come back to bite me later?
const EventEmitter = require('events');
const emitter = new EventEmitter();
const syncListener = () => {
console.log('sync bar ');
};
const asyncListener = async () => {
console.log('async bar');
};
emitter.on('foo', asyncListener);
emitter.on('foo', syncListener);
emitter.emit('foo');
Upvotes: 9
Views: 9901
Reputation: 3861
As the doc states:
Using async functions with event handlers is problematic, because it can lead to an unhandled rejection in case of a thrown exception
https://nodejs.org/api/events.html#events_capture_rejections_of_promises
the recommendation is to not use async functions as 'error' event handlers.
Upvotes: 2
Reputation: 228
The return value of event handlers is completely ignored. From the documentation:
When the
EventEmitter
object emits an event, all of the functions attached to that specific event are called synchronously. Any values returned by the called listeners are ignored and will be discarded.
So marking a listener as async (in other words, returning a promise) doesn't matter, except as @Ry mentions with possibly unhandled exceptions. If you need processing of events to happen in sequence then you may have to do something further (you may also want to check out the asynchronous vs synchronous documentation)
Upvotes: 10
Reputation: 1265
Well, no, not that I know of. I use async functions in EventEmitter callbacks absolutely everywhere in my code. From what I can tell, there's no downside.
Upvotes: 1