With the following function I am trying to calculate the total price of a checkout. But if I console.log() the variable before it is returned, I get 0. If I console.log() the variable in the findOne() function, I get the correct value.
As database I use MongoDB and "Item" is a model.
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;
}
I'm desperate about it and I don't really know what to look for on the internet. Many thanks for answers in advance.