示例代码:
import { EventEmitter } from 'node:events'
let bus = new EventEmitter()
async function demo(){
let foo
const listen = async function (channelName, callback){
await bus.on(channelName, data => { callback(data) })
}
await listen('test', data => {
foo = data
})
// Artificially introducing a delay fixes this
// while (foo == undefined){ await new Promise(resolve => setTimeout(resolve, 1000)) }
// but without the day returns 'undefined'
console.log(foo)
}
demo()
我怀疑这只是我不熟悉正确的异步语法/结构的问题。
我尝试了十几种添加“等待”的变体,但没有成功。
信息赞赏!
您需要创建一个在
on
事件发生时解决的承诺。您可以使用 new Promise
并在该事件发生时调用 resolve
来完成此操作。
类似:
const channelData = (bus, channelName) =>
new Promise(resolve => bus.on(channelName, resolve));
async function demo() {
const foo = await channelData(bus, 'test');
console.log(foo);
}
demo();