0

I am using https://www.npmjs.com/package/pdf2json npm package which will pick the pdf from the given path and when the pdf parser is ready to parse it, then it triggers an event pdfParser_dataReady. I want to user this along with async await.

const defineParser = function (path) {
  let pdfParser = new PDFParser();
  pdfParser.loadPDF(path);

  pdfParser.on('pdfParser_dataError', (errData) => console.error(errData.data));
  pdfParser.on('pdfParser_dataReady', (pdfData) => {
    return initPdfParser(path, pdfData);
  });
};

In the above code inside pdfParser_dataReady i am calling a initPdfParser which will return some data. And defineParser function is called from some other function in an async manner.

const uploadEmailDoc = async function (req, h) {
  const path = `./controllers/${req.payload.file.hapi.filename}`;
  // some operation here
  await fs.writeFileSync(path, req.payload.file._data);
  return await defineParser(path);
};

My QUESTION is how can i use async await in the above case, so that defineParser function will wait till the pdfParser_dataReady event gets triggered and returns the data from the initPdfParser function, so that uploadEmailDoc will get the final data and return it. I tried couple of ways, but couldn't find a way to get the response from event callback.

Any help would be really appreciated.

Rajeshwar
  • 2,290
  • 4
  • 31
  • 41
  • It looks like the `pdfParser_dataError` and `pdfParser_dataReady` events are one-offs, so you'd wrap this in a promise just like any other callback-based API; then used the wrapped version. See the answers to the [linked question](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises). Fundamentally, `return new Promise((resolve, reject) => { /* ... */ });` and in the body of that function, call `reject` if you get an error and `resolve` if you get success. – T.J. Crowder Apr 14 '20 at 16:21
  • Ok, i will try that out. – Rajeshwar Apr 14 '20 at 17:00

0 Answers0