Javascript Async/await Execution Order Problem In For...of, For Await...of And Promise.all
For each object (product) in an array (products), I'm getting the price from a mongoose database. That value (prodDB.price) is summed to the 'amount' variable initialized as 0 befo
Solution 1:
The problem is that you are mixing "callback" mode and "await" mode. Either await
the operation, or give it a callback, otherwise it gets messy.
for (const product of products) {
let prodDB = awaitProduct.findById(product._id).lean().exec(); // add lean() to get only JSON data, lighter and faster
amount += product.count * prodDB.price;
console.log("Current amount", amount);
};
However, this is very expensive, because if you have 10 products, you call your database 10 times. Better call it only once and fetch all _id in one go.
let allIds = products.map(p => p._id),
prodDBs = awaitProduct.find({
_id: {
$in: allIds
}
})
.lean()
.exec()
const amount = prodDBs.reduce((a,b) => a.price + b.price, 0)
Solution 2:
I would use Promise.all
so you can run all the DB request in parallel and wait for all them to complete, instead of running all of them in series. The only issue I think is with .exec()
not returning a Promise
, just use findById()
that returns a Promise, try this code:
let amount = 0;
awaitPromise.all(products.map(async (product)=> {
const prodDB = awaitProduct.findById(product._id)
amount += product.count * prodDB.price
}));
Post a Comment for "Javascript Async/await Execution Order Problem In For...of, For Await...of And Promise.all"