我正在编写一个 Node.js v10 应用程序,我想在事件监听器函数中使用 await
,因此我制作了一个 async
监听器函数。根据下面的代码,它似乎可以工作。
但我很好奇在使用 on( )
方法?有什么东西可能会回来咬我?
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');
最佳答案
事件处理程序的返回值被完全忽略。来自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.
因此,将监听器标记为异步(换句话说,返回 promise )并不重要,除非@Ry 提到了可能未处理的异常。如果您需要按顺序处理事件,那么您可能需要做一些进一步的事情(您可能还想查看 asynchronous vs synchronous documentation )
关于javascript - 使用 async 函数作为 EventEmitter 监听器有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55881889/