我正在尝试从数据库中检索一堆产品价格,并假设我可以通过它们进行映射或查找,并将价格 += 到变量上,如下所示:
// Get Total
exports.getTotal = (req,res) => {
let productList = req.body;
let total = 0;
const results = productList.map(async (product) => {
Product.findById(product._id)
.select('price')
.exec((err, foundProduct) => {
if (err){
console.log(`Error: Product with id ${product._id} not found.`);
} else {
console.log('Product price. ', foundProduct.price);
total += foundProduct;
}
})
});
Promise.all(results).then(data => console.log('Total is', total));
};
但是,总计的 console.log 始终返回 0。我怀疑这是 console.log 在 map 和数据库查找 promise 完成之前运行的问题。
感谢任何指导。
最佳答案
您以错误的方式使用 exec Exec 向您返回一个 promise 。您可以像这样简化
// Get Total
exports.getTotal = (req, res) => {
const productList = req.body;
let total = 0;
const results = productList.map(async product => {
const foundProduct = await Product.findById(product._id).exec();
total += foundProduct;
return foundProduct;
});
Promise.all(results).then(data => console.log("Total is", total));
};
关于javascript - 使用 map 或 foreach 进行异步/等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60634777/