-1

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);
MK BOZ
  • 1
  • 1

1 Answers1

0

Try this :

const { userId, products } = req.body;

const user = User.findById(userId)
var fullPrice = 0;

let promises = []

products.forEach(async product => {
    promises.push(new Promise(async (resolve,reject)=>{
    try {
        const foundProduct = await Product.findOne({ _id: product.productId });
        const calculatedPrice = await foundProduct.price * product.quantity;
        fullPrice += calculatedPrice;
        // Displays a number of calculated prices
        resolve(fullPrice.toFixed(2));
    } catch (error) {
        reject(error)
    }
    }))
})

// Displays 0
Promise.all(promises).then((messages)=>{
    console.log(messages)
    console.log(fullPrice);                 // <---- it will wait for all the promises to finish and then run console.log
}).catch((error)=>{
    console.log(error)
})
  • 1. No point in creating a new promise just to wrap another promise, `Product.findOne(...)` in this case. 2. Executor function shouldn't be an async function. – Yousaf Aug 06 '22 at 12:02