title: Nodejs Iterate through array and write to file
body: <p>I have an array contains around 20K records. Each record contains one encrypted column and rest of them are not. When I iterate through each record using for loop and call the decrypt callback function, the result is coming up later hence the decrypted value are always null. After decrypting I want to write entire row to excel sheet and close the file after every element in array is written to the file. What is the best way to do so?</p>
  
  <pre><code>var myArray = [{name:'ABC',accountNumber:'hsjdhsj%^==='},{name:'BCD',accountNumber:'hsjdhsj%^==='}];
  for(var i=0; i&lt; myArray.length; i++){
     myArray[i].decryptAccNumber = decrypt(myArray[i].accountNumber);  // async way to decrypt it 
     res.write(myArray[i]); //Writing to excel file
  }
  res.close();
  </code></pre>
  
  <p>Now, the file contains only name, account number but not decrypted account number.</p>
  
  <p>Any advise on how to proceed with such requirement that is mixing of sync &amp; async</p>
  
  <p>---------- Edited ------------------------</p>
  
  <pre><code>var callbackCount = myArray.length;
  for(var i=0; i&lt; myArray.length; i++)
  {
     decrypt(myArray[i].accountNumber,function(decrypted){  
       myArray[i].decryptAccNumber=decrypted;
       res.write(myArray[i]); //Writing to excel file
       callbackCount--;
       if(callbackCount === 0){
         res.close();
       }
    });
  }
  </code></pre>
  
  <p>This is the solution given at <a href="https://gist.github.com/Grety/236c41acf006475f0eee768b64e4a7bc" rel="nofollow">https://gist.github.com/Grety/236c41acf006475f0eee768b64e4a7bc</a> 
  Even, I thought the same solution but personally I did not like this solution as it looks like work around.
  Is there any other better way to solve this problem other than using temp variable like callbackCounter? This is the exact problem what I want to posted. Thanks to Kyrylo Slatin for posting GIT url with exact problem. </p>