0

In my API while POST the route , i have to find the list of products which current user have in his Cart. I am having current user details then whenever i try to apply forEach loop on cart to extract information from my Products collection and pushing that info to new array and printing that new array, it is showing empty. while printing it inside forEach shows the data. How do i fix it so it also prints the new array data?

  BuyerRoute.post("/Orders", verifyToken,async(req,res) =>{
    let buyer = await Buyer.findById(res.current_user.buyer_user._id)
    
    var e = []
    buyer.Buyer_Cart.forEach( async (prodObj) => {
        let products = await Products.findById(prodObj.Product_ID)
        e.push(products)
        
    })
    console.log(e)
   })

Output: []

While inside the forEach loop

    BuyerRoute.post("/Orders", verifyToken,async(req,res) =>{
    let buyer = await Buyer.findById(res.current_user.buyer_user._id)
    
    var e = []
    buyer.Buyer_Cart.forEach( async (prodObj) => {
        let products = await Products.findById(prodObj.Product_ID)
        e.push(products)
        console.log(e)
        
    })})

Output:

[
  {
    _id: new ObjectId("6381b9b4c5efd30fe8492902"),
    Product_name: 'headphones',
    Product_description: 'headphones for PC',
    Product_price: 500,
    Quantity_available: 10,
    seller_Id: '6381b7f3fdc04885a28723c1',
    seller_name: 'xyz',
    __v: 0
  }
]
4
  • 1
    In your first example console.log(e) gets called before the e.push() happens because you are awaiting something before that. To handle async code I'd recommend you use Promise.all (for example, depending on your needs) and Array.prototype.map. Commented Nov 28, 2022 at 11:41
  • You should do: let e = await Promise.all(buyer.Buyer_Cart.map(prodObj => Products.findById(prodObj.Product_ID))) Commented Nov 28, 2022 at 11:42
  • The post and forEach callbacks are asynchorize functions, so the output of your first code snippet does not wait until the results return, and got empty, however the second one can print inside the callback. Maybe you can make your forEach call async and so await the results. Commented Nov 28, 2022 at 11:46
  • Promise.all and map function works like a charm !!! thank you!! Commented Nov 28, 2022 at 11:48

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.