繁体   English   中英

对于循环、等待和承诺 - Javascript

[英]For loops, await, and promises - Javascript

我正在尝试使用 for 循环遍历数组并在每个项目上执行异步 function。 我希望这按顺序发生,并且我不希望数组中下一个项目的下一个异步 function 执行,直到前一个项目的异步 function 完成。

我正在使用 await 并承诺尝试这样做。 但是,我一定做错了什么,因为代码似乎无法正常工作。 我在其他帖子上做了一些阅读; 但是,我无法理解下面看到的代码有什么问题。

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

我在控制台上得到的 output 是:

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

我究竟做错了什么?

您应该在 asyncFunc 中返回asyncFunc以便await关键字将等待直到它解决。 所以把它改成这样:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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