Reputation: 37
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?
Upvotes: 2
Views: 2233
Reputation: 6289
For the sake of clarity regarding the actual issue you ran into, the problem is with this block of your code:
return new Promise((resolve, reject) => {
resolve;
});
The problem is that resolve
needs to be a function that actually executes. Thus what you needed was this:
return new Promise((resolve, reject) => {
resolve();
});
Upvotes: 1
Reputation: 1486
So, you are returning two promises, which is a problem because you resolve one only to create a second which the main thread is then waiting on. All you have to do is return the promise that db.collection... gives you.
Fundamentally, the problem is that the new promise you create isn't resolved properly. You just say that the promise is (resolve, reject) => {resolve;}
which is A) not even really a function and B) not going to resolve. Because you didn't call the resolve function. Truly though, this promise should never have been created because it was completely unnecessary, so I would worry more about just handling promises with simple awaits and returns than bothering with creating them. TL;DR Don't create a promise if there is already a promise that exists which you can use.
This code should work:
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(() =>{
let d = new Date();
console.log(i + " async COMPLETED at: " + d.getTime());
});
}
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();
Upvotes: 1