I'm making a payment system using Stripe and I want to create an order by searching the price on the database and then multiply it with the order quantity. However when the forEach loop is finished it doesn't display the total sum on the console. It console logs before the fullPrice has been updated. How do I fix this?
const { userId, products } = req.body;
const user = User.findById(userId)
var fullPrice = 0;
products.forEach(async product => {
try {
const foundProduct = await Product.findOne({ _id: product.productId });
const calculatedPrice = await foundProduct.price * product.quantity;
fullPrice += calculatedPrice;
// Displays a number of calculated prices
console.log(fullPrice.toFixed(2));
} catch (error) {
console.log(error);
}
})
// Displays 0
console.log(fullPrice);