node.js - 如何在 JS 的循环中使用猫鼬函数
问题描述
我正在使用“request-promise”模块从某些 API 获取数据。
这将数组值作为主体。
我想将该数组保存为 mongoDB 中的每个文档。
因此,我用'for'作为循环。
但是当我用 console.log 检查这个时,
我希望像下面这样。
Current i is : 0
orderFind
Current i is : 1
orderFind
Current i is : 2
orderFind
Current i is : 3
orderFind
然而它给了我
Current i is : 0
Current i is : 1
Current i is : 2
Current i is : 3
orderFind
orderFind
orderFind
orderFind
我试过异步,等待也。但是效果不好。。
exports.saveOrder = (req, res) => {
rp({
method: "GET",
uri: "https://robot.com",
json: true
}).then(body => {
for (let i = 0; i < body.length; i += 1) {
console.log(`Current i is : ${i}`);
const eachBody = body[i];
Order.findOne(
{
order_id: eachBody.order_id
},
(err, exOrder) => {
console.log("orderFind");
if (err) {
return res.send(err);
}
}
);
}
});
};
解决方案
检查此代码,使用async/await
您可以解决问题
exports.saveOrder = (req, res) => {
rp({
method: "GET",
uri: "https://robot.com",
json: true
}).then(async body => {
for (let i = 0; i < body.length; i += 1) {
console.log(`Current i is : ${i}`);
const eachBody = body[i];
try {
const result = await Order.findOne({ order_id: eachBody.order_id });
console.log(result);
} catch (e) {
return res.send(e);
}
}
});
};
推荐阅读
- python - PyMc3:后验预测检查导致错误
- python - 如何创建通过迭代运行的累积代码?
- linux - linux下shebang不拆分参数
- docker-compose - 我如何在 haproxy 后面使用 wso2
- angular6 - Angular 6:在生产中禁用管道转换
- python - n 个长度为 l 的项目的所有组合,其中 n < l
- python-3.6 - python 3编程彩票号码生成器
- android - React Native Router Flux - 期望一个组件类,当单击按钮转到另一个屏幕时得到 [object Object]
- c# - 在 C# 中验证 IP
- javascript - 只允许一个函数使用包装函数运行 n 次