0

If I console.log my cartProducts in the forEach() loop, then it works fine, and it stores all the products. But if I console.log my cartProducts outside the loop, then it prints an empty array.

var cartProducts = []; const cart = await CartModel .findOne({ UserDetailsId: userID }) .populate('UserDetailsId'); if (cart) { cart.products.forEach(async(product) => { const productItem = await ProductModel .findOne({_id: product.productDetailsId }); cartProducts.push(productItem); }); } console.log("Cart Items", cartProducts); 
2
  • 1
    Use native for loop for async loops. Commented Jul 9, 2020 at 17:40
  • Maybe it prints an empty array, because you are pushing the objects asynchronously to the array and log therefore too early to the console? You could log inside the async iterations and keep the final console.log call to check this. Commented Jul 9, 2020 at 17:42

2 Answers 2

2

Try to get all product ids by:

const productIds = cart.products.map(product => product.productDetailsId); 

Then you can get all product items once without sending multiple request to the DB:

const products = await ProductModel.find({_id: {$in: productIds} }); 
Sign up to request clarification or add additional context in comments.

Comments

0

To do it that way you need to make your forEach async

if (cart) { async function asyncForEach(arr) { const promises = arr.products.forEach(async(product) => { const productItem = await ProductModel .findOne({_id: product.productDetailsId }); cartProducts.push(productItem); }); await Promise.all(promises); } asyncForEach(cart); } 

function mockAsync(param) { return new Promise((resolve, reject) => { setTimeout(() => resolve(console.log(param)), 2000) }) } let cart = ["A", "B", "C"]; async function asyncForEach(arr) { console.log("processing...") const promises = arr.forEach(async(product) => { await mockAsync(product); }); await Promise.all(promises) } asyncForEach(cart);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.