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;
    }
  }
}
