使用下面的函数,我试图计算一次结账的总价。 但如果我在返回变量之前将它作为console.log(),则得到0。 如果我console.log()findOne()函数中的变量,我将得到正确的值。
作为数据库,我使用MongoDB,“item”是一个模型。
function calculateOrderAmount(items) {
var totalPayment=0;
items.forEach((item) => {
Item.findOne( { _id: item } )
.then(item => {
if(item) {
// Item exists
totalPayment = item.price;
console.log(totalPayment);
}
});
});
console.log(totalPayment);
return totalPayment;
}
我对此感到绝望,我真的不知道该在互联网上寻找什么。 非常感谢你提前回答我的问题。
item.findone
是一个异步操作,因此在代码中执行:
VaR totalPayment=0
items.foreach((item)=>{...
console.log(totalPayment)
返回总付款
CalculateOrderAmount
item.findone
的回调您必须使用回调sytle或async
函数,如下所示:
async function calculateOrderAmount (items) {
// beware: if you have a huge items list, doing so could lead to high memory usage
const itemsPromises = items.map((item) => {
return Item.findOne({ _id: item })
.then(item => {
if(item) {
// Item exists
return item.price;
}
return 0
});
})
const prices = await Promise.all(itemsPromises)
const totalPayment = prices.reduce((a, b) => a + b, 0)
console.log(totalPayment)
return totalPayment
}