本文介绍了如何在NodeJS中为For Loop提供Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何阻止nodeJS执行for循环外的语句,直到循环完成?

How to stop nodeJS to execute statements written outside for loop till for loop is completed?

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是空的。

The problem is that the statement after For Loop is being executed before For loop, so the licensesArray is empty when i receive the API Data.

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

Any clue how to do that?

非常感谢你。

推荐答案

使用 async / await

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

如果您的环境支持,我会选择 async / await ,如它使事情更易于阅读,并允许您使用同步思维模式进行编程(在引擎盖下它仍然是异步的)。如果您的环境不支持,您可以使用 Promise.all 方法。

I would go with async/await if your environment supports it, as it makes things easier to read and lets you program with a synchronous mindset (under the hood it's still asynchronous). If your environment does not support it, you can go with the Promise.all approach.

进一步阅读:




  • async function
  • Promise.all

这篇关于如何在NodeJS中为For Loop提供Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 16:36