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');
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');
Share
Improve this question
edited Apr 27, 2019 at 19:41
Moglum
asked Apr 27, 2019 at 15:06
MoglumMoglum
1432 silver badges7 bronze badges
1
- 2 You risk unhandled rejections, but if your async functions never throw or you intend whatever happens with unhandled rejections in your environment then it’s fine. – Ry- ♦ Commented Apr 27, 2019 at 19:44
3 Answers
Reset to default 10The 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)
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.
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.