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?
var myArray = [{name:'ABC',accountNumber:'hsjdhsj%^==='},{name:'BCD',accountNumber:'hsjdhsj%^==='}];
for(var i=0; i< 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();
Now, the file contains only name, account number but not decrypted account number.
Any advise on how to proceed with such requirement that is mixing of sync & async
---------- Edited ------------------------
var callbackCount = myArray.length;
for(var i=0; i< 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();
}
});
}
This is the solution given at https://gist.github.com/Grety/236c41acf006475f0eee768b64e4a7bc 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.