Sample code:
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()
I suspect this is just an issue of me not being familiar with the correct async syntax / structure.
I have tried a dozen variations of adding 'await', but no luck.
Info appreciated!
thanks to trincot at the answer below, and the same method at this comment, it's up and working
You'll need to create a promise that resolves when the
onevent occurs. This you can do withnew Promiseand callingresolvewhen that event occurs.Something like: