0

In this case, there is nothing easier to wait until the data is received, and then resolve the Promise:

// Using Promise resolve/reject
module.exports = () => {
   return new Promise(async (resolve, reject) => {
      let doc = await Document();
      doc.on('data', async (data) => {
         resolve(data);
      });
   })
}

But what do I do in this case?

// Using async/await
module.exports = async () => {
   let doc = await Document();
   doc.on('data', (data) => {
      // ???
   });
}
John Lenson
  • 167
  • 2
  • 9

1 Answers1

1

You still need the new Promise, you just should use it as the operand of an await inside the async function, not using an async function as the executor:

module.exports = async () => {
    const doc = await Document();
    return new Promise(resolve, reject) => {
        doc.on('data', resolve);
    });
};

However, I would recommend to use once instead of on so that the event handler is removed after the first occurrence of the event - the promise can be resolve only once anyway. Also if you have node v11.13.0 or higher you can just use the events.once method so that you don't have to build the promise yourself - and it also handles error events correctly:

const { once } = require('events');

module.exports = async () => {
    const doc = await Document();
    return once(doc, 'data');
};
Bergi
  • 630,263
  • 148
  • 957
  • 1,375