I am trying to use a for loop to iterate through an array and perform an async function on each item. I want this to happen in a sequential order and I don't want the next async function for the next item in the array to execute until the async function for the previous item has COMPLETED.
I am using await and promises to try to do this. However, I must be doing something wrong because the code does not seem to be working right. The for loop only seems to work once.
Here is my code:
function asyncFunc(i)
{
//Here I am updating my database which is the async part of this function
return db.collection("collection").doc("doc").update({
})
.then(function(){
let d = new Date();
console.log(i + " async COMPLETED at: " + d.getTime());
return new Promise((resolve, reject) => {
resolve;
});
});
}
async function doWork()
{
var numbers = [1,2,3,4];
for(const i of numbers)
{
var d = new Date();
console.log(i + " async CALLED at: " + d.getTime());
await asyncFunc(i);
}
}
doWork();
Here is the console output:
1 async CALLED at: 1594683980009
1 async COMPLETED at: 1594683980280
Why is this happening?