Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for a stream to finish piping? (Nodejs)

I have a for loop array of promises, so I used Promise.all to go through them and called then afterwards.

let promises = []; promises.push(promise1); promises.push(promise2); promises.push(promise3);  Promise.all(promises).then((responses) => {   for (let i = 0; i < promises.length; i++) {     if (promise.property === something) {       //do something     } else {       let file = fs.createWriteStream('./hello.pdf');       let stream = responses[i].pipe(file);       /*          I WANT THE PIPING AND THE FOLLOWING CODE           TO RUN BEFORE NEXT ITERATION OF FOR LOOP       */       stream.on('finish', () => {         //extract the text out of the pdf         extract(filePath, {splitPages: false}, (err, text) => {         if (err) {           console.log(err);         } else {           arrayOfDocuments[i].text_contents = text;         }       });     });       } } 

promise1, promise2, and promise3 are some http requests, and if one of them is an application/pdf, then I write it to a stream and parse the text out of it. But this code runs the next iteration before parsing the test out of the pdf. Is there a way to make the code wait until the piping to the stream and extracting are finished before moving on to the next iteration?

like image 366
ThePumpkinMaster Avatar asked Jun 15 '16 13:06

ThePumpkinMaster


1 Answers

Without async/await, it's quite nasty. With async/await, just do this:

Promise.all(promises).then(async (responses) => {   for (...) {     await new Promise(fulfill => stream.on("finish", fulfill));     //extract the text out of the PDF   } }) 
like image 113
Sarsaparilla Avatar answered Oct 02 '22 03:10

Sarsaparilla