简体   繁体   中英

For loops, await, and promises - Javascript

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. I have done some reading on other posts; however, I am not able to understand what is wrong with my code that is seen below.

function asyncFunc(i)
{
  //Here I am updating my database which is the async part of this function
  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();

The output that I get on my console is:

1 async CALLED at: 1594674023549
2 async CALLED at: 1594674023556
3 async CALLED at: 1594674023556
4 async CALLED at: 1594674023557
1 async COMPLETED at: 1594674023852
2 async COMPLETED at: 1594674023943
3 async COMPLETED at: 1594674024033
4 async COMPLETED at: 1594674024140

What am I doing wrong?

You should return the promise in asyncFunc so that the await keyword will wait until it resolves. So change it to this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM