0
User.find({}, function(error, cartUser){
        if (error) {
          const error = new Error(err);
          error.httpStatusCode = 500;
          return next(error);
        } 
      
        let cartUserArray = []
        cartUser.forEach(u => {
          
        if(u.cart.items.length > 0){
          u
          .populate('cart.items.productId')
          .execPopulate()
          .then(user => {
            
            cartUserArray.push(user)
            console.log("cartUserArray 1" + cartUserArray);
            return cartUserArray
            
          })
          
          console.log("cartUserArray 2" + cartUserArray);
          return cartUserArray
        }
       })
       console.log("cartUserArray 3" + cartUserArray);
      const products = cartUserArray
      res.render('shop/cart', {
        path: '/cart',
        pageTitle: 'Your Cart',
        products: products
      });
      
      })
Result
cartUserArray 2
cartUserArray 2
cartUserArray 3
cartUserArray 1{
  cart: { items: [ [Object], [Object] ] },
  role: 'user',
  _id: 645fb212aa2e1cd207052f6b,
  name: 'user1',
  email: 'user1@user.com',
  phone: 1234567,
  password: '$2a$12$jEfix45P2PmFDZQeRsg4/e5GnZgmtnYxNFYk5wotvbMM3pTgZN8JK',
  __v: 0
}
cartUserArray 1{
  cart: { items: [ [Object], [Object] ] },
  role: 'user',
  _id: 645fb212aa2e1cd207052f6b,
  name: 'user1',
  email: 'user1@user.com',
  phone: 1234567,,
  password: '$2a$12$jEfix45P2PmFDZQeRsg4/e5GnZgmtnYxNFYk5wotvbMM3pTgZN8JK',
  __v: 0
}

Hi, I would like to ask, why my log "cartUserArray 3" cannot get data? I want to put the "cartUserArray" into "const products" and render it out to the website. but it seems I cannot get the data outside the foreach function. thanks for the help

  • See [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – Guy Incognito May 14 '23 at 15:31

0 Answers0