node.jseventseventemitter

Is it possible to asynchronously wait for a Node.js Event Emitter 'event.on()' to populate, before executing the rest of the function?


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


Solution

  • You'll need to create a promise that resolves when the on event occurs. This you can do with new Promise and calling resolve when that event occurs.

    Something like:

    const channelData = (bus, channelName) => 
        new Promise(resolve => bus.on(channelName, resolve));
    
    async function demo() {
        const foo = await channelData(bus, 'test');
        console.log(foo);
    }
    
    demo();