0

I have a list of items, and each item have a list of instructions. Each item will be printed out into a PDF file with each instruction occupying one page and saved locally. What i have now is a for loop which queries the database for the instructions of each item, and after populating the PDF pipe it out to a path. The problem is due to the query being async, only the last PDF being piped can be opened, the rest are corrupted. How do i overcome this? My code is as shown below.

var counter = 0
for (var o=0; o<itemList.length; ++o){
  Steps.find( {itemid:itemid[o], sort: "sequence asc"} ).exec( function(err,steps){
    doc[counter] = new PDFDocument();
    if(!err){
      doc[counter].pipe( fs.createWriteStream(path + "DocName" + counter + ".pdf") );
      for (var x=0; x<steps.length; ++x){
        doc[counter].text("Instructions: " + steps[x].instruction.font('Times-Roman', 13);
      }
      ***/*if (counter == itemList.length-1){
        doc[counter].end();
      }*/***
      //That is the problem, i shouldn't have done the check and end the doc immediately, that solved the issue.
      doc[counter].end();

      ++counter;
    }
  }
}
Cherple
  • 725
  • 3
  • 10
  • 24
  • Use any one of these: `callback`, `promise`, or `async/await`. Popular libraries are [async](http://caolan.github.io/async/), [bluebird](http://bluebirdjs.com/docs/getting-started.html). Which version of node are you using? – Sangharsh Mar 27 '17 at 09:27
  • Also check http://stackoverflow.com/q/14220321/1435132 – Sangharsh Mar 27 '17 at 09:29

1 Answers1

0

Edited the question to show the working solution. A careless mistake where i only do a doc.end() after the last file is written, instead of ending it after every single file.

Cherple
  • 725
  • 3
  • 10
  • 24