javascript - 如何在 NodeJS 中为 For 循环提供 Promise

标签 javascript node.js mongodb reactjs

如何阻止nodeJS执行for循环外写的语句直到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 为空。

知道怎么做吗?

会感谢你的。

最佳答案

使用异步/等待:

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 方法。

进一步阅读:

关于javascript - 如何在 NodeJS 中为 For 循环提供 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47731873/

相关文章:

javascript - 尝试将变量加载到 Angular 指令中

javascript - 隐藏没有JavaScript的HTML元素,只有CSS

javascript - 将页面内容加载到一页(重复内容)对 SEO 不利?

node.js - 如何在同步模式下运行 Node shelljs 并获取标准输出和标准错误

javascript - javascript中循环引用有什么用

node.js - 类型错误 : undefined is not a function in nodejs

MongoDB WinningPlan IDHACK

node.js - 如何在 Node.js Express mongoose 后端的 URL 查询字符串中使用 $or 运算符

mongodb - 如何使用 Doctrine ODM for MongoDB 设置我自己的 MongoId?

node.js - 序列化时间戳名称