Search code examples
javascripttypescriptasync-awaitpromisenestjs

Promisify an event handler


I am trying to use https://github.com/yfinkelstein/node-zookeeper to connect to zookeeper server. node-zookeeper uses EventEmitter's on function to allow using the zookeeper client when it connects successfully.

this.client.on('connect', async () => {
  console.log('connected successfully');
  // fetch data from zookeeper by supplying path
  const data = await client.get('/config', false);
  console.log(data); 
 });
 

But this does not allow me to return the data. If this data represents configuration, it is important to be able to return it. I tried promisifying using bluebird but no luck.

How can I promisify it (or any other way that would allow me to return the values).


Solution

  • If you want to access data from outside of the event listener, you can use the Promise constructor:

    const data = await new Promise(resolve => 
      this.client.on('connect', async () => {
        console.log('connected successfully');
        // fetch data from zookeeper by supplying path
        resolve(await client.get('/config', false));
      })
    );
    console.log(data);