[英]How do I wait for a for loop with a callback function inside to finish before I render a page in Mongoose
I have a collection of users and products.我有一组用户和产品。 Every user has a 'cart' field which is an array of IDs of the products.每个用户都有一个“购物车”字段,它是产品 ID 的数组。 When a user clicks on the cart I need Mongoose to find the users cart, then loop through the array and for each item (the product ID) I need Mongoose to find the product in the products collection to display the image and the name.当用户点击购物车时,我需要 Mongoose 来找到用户购物车,然后遍历数组,对于每个项目(产品 ID),我需要 Mongoose 来在产品集合中找到产品以显示图像和名称。 The problem is that I don't know how to render the page only after all the products have been put into the cartItems array.问题是我不知道如何在所有产品都放入 cartItems 数组后才呈现页面。 This is my first time asking a question here, so please ask me anything if I didn't explain it well.这是我第一次在这里提问,所以如果我解释得不好,请问我。
app.get("/cart", (req, res) => {
User.findById(req.user._id, (err, foundUser) => {
if(!err) {
let itemIDs = foundUser.cart;
let cartItems = []
for (const itemID of itemIDs) {
Product.findById(itemID, (err, foundItem) => {
if(!err) {
cartItems.push(foundItem);
} else {
console.log(err);
}
})
}
console.log(cartItems);
res.render("cart", {user: req.user, products: cartItems});
} else {
console.log(err);
}
})
})
There are multiple ways to achieve it.有多种方法可以实现它。
You can find all items at once:您可以一次找到所有项目:
Product.find({_id: {$in: itemIDs}}).then(...)
Use async, await for readable code:使用异步,等待可读代码:
app.get("/cart", async (req, res) => { const user = await User.findById(req.user._id); const itemIDs = user.cart; const items = await Product.find({_id: {$in: itemIDs}}); res.render("cart", {user: req.user, products: items}); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.