【发布时间】:2021-01-27 22:48:59
【问题描述】:
对于数组(产品)中的每个对象(产品),我从猫鼬数据库中获取价格。该值 (prodDB.price) 与循环前初始化为 0 的“金额”变量相加。
我尝试了其他问题中解释的 3 个解决方案,其中:
- 为的
- 等待的
- Promise.all
---对于---
let amount = 0;
for (const product of products) {
await Product.findById(product._id).exec((err, prodDB)=> {
amount += product.count * prodDB.price;
console.log("Current amount", amount);
});
};
console.log("Amount total", amount);
--- 等待 ---
let amount = 0;
for await (const product of products) {
Product.findById(product._id).exec((err, prodDB)=> {
amount += product.count * prodDB.price;
console.log("Current amount", amount);
});
};
console.log("Amount total", amount);
--- Promise.all ---
let amount = 0;
await Promise.all(products.map(async (product)=> {
await Product.findById(product._id).exec((err, prodDB)=> {
amount += product.count * prodDB.price;
console.log("Current amount", amount);
});
}));
console.log("Amount total", amount);
任何以前版本的代码的结果总是相同的,而且是出乎意料的,尤其是 console.log 发生的顺序:
Amount total 0
Current amount 10.29
Current amount 17.15
Current amount 18.29
Current amount 19.45
Current amount 43.2
你能帮忙吗? 非常感谢!
【问题讨论】:
标签: javascript loops promise async-await