如何在NodeJS中给予For循环承诺

如何停止nodeJS执行循环写入的语句,直到for循环完成?

for(i=0;i<=countFromRequest;i++) { REQUEST TO MODEL => then getting result here (its an object) licensesArray.push(obj.key); } res.status(200).send({info:"Done Releasing Bulk Licenses!!!",licensesArray:licensesArray}) 

问题是For循环之后的语句在For循环之前执行,所以当我收到API数据时licensesArray是空的。

任何线索如何做到这一点?

将感谢你。

使用asynchronous/等待

 const licensesArray = []; for(let i = 0; i <= countFromRequest; i++) { const obj = await requestModel(); // wait for model and get resolved value licensesArray.push(obj.key); } res.status(200).send({licensesArray}); 

使用Promise.all

 const pArr = []; const licensesArray = []; for(let i = 0; i <= countFromRequest; i++) { pArr.push(requestModel().then(obj => { licensesArray.push(obj.key); })); } Promise.all(pArr).then(() => { // wait for all promises to resolve res.status(200).send({licensesArray}); }); 

如果你的环境支持它,我会去asynchronous/等待 ,因为它使事情变得更容易阅读,并让你用同步的思维方式进行编程(在底层,它仍然是asynchronous的)。 如果你的环境不支持它,你可以使用Promise.all方法。

进一步阅读:

  • asynchronousfunction
  • Promise.all