Home > OS >  How do I wait for a for loop with a callback function inside to finish before I render a page in Mon
How do I wait for a for loop with a callback function inside to finish before I render a page in Mon

Time:01-31

I have a collection of users and products. Every user has a 'cart' field which is an array of IDs of the products. 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. 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. 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);
        }
    })

})

CodePudding user response:

There are multiple ways to achieve it.

  1. You can find all items at once:

    Product.find({_id: {$in: itemIDs}}).then(...)
    
  2. 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});
    }
    
  • Related