对于数组(产品)中的每个对象(产品),我从猫鼬数据库中获取价格。该值 (prodDB.price) 与在循环之前初始化为 0 的“金额”变量相加。
我尝试了其他问题中解释的 3 种解决方案,其中:
对于
等待
承诺.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
你能帮忙吗?非常感谢!
萧十郎
SMILET
相关分类