使用 async 函数作为 EventEmitter 监听器有什么问题吗?

Is there any problem with using async function as an EventEmitter listener?

我正在编写一个 Node.js v10 应用程序,我想在事件侦听器函数中使用 await,所以我制作了一个 async 侦听器函数。根据下面的代码,它似乎可以工作。

但我很好奇在使用 on() 方法将 async 函数注册为 EvenEmitter 侦听器时是否存在隐藏的缺点或我应该注意的事项?以后有什么东西可能会回来咬我?

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');

嗯,不,据我所知没有。我在代码的任何地方都在 EventEmitter 回调中使用异步函数。据我所知,没有缺点。

事件处理程序的 return 值被完全忽略。来自 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.

因此将侦听器标记为异步(换句话说,return 承诺)并不重要,除非 @Ry 提到可能存在未处理的异常。如果您需要按顺序处理事件,那么您可能需要做一些进一步的事情(您可能还想查看 asynchronous vs synchronous documentation

如文档所述:

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.