Home > Software design >  array push is not updated inside a loop in node js
array push is not updated inside a loop in node js

Time:04-25

trying push in array inside a loop

exports.bulkCartUpdate = async (req, res) => {
    
    let userId = req.params.userId;
    let CartId = req.profile.CartId;
    let items = req.body;

var promises = [];
      for( let i of items )
      {
         const productId = i.productId;
         const quantity = i.quantity;
         
          await Product.findById(productId).exec((err, productdet) => {
        
          let obj = {
            productId,
            quantity,
            price: productdet.price,
            name: productdet.name,
            stock: productdet.inventory
          }
         promises.push(obj);

        });
            console.log(promises);
      }
}

The above code is to get some details from api and make an object to push array . but it shows empty. Please help me , Thanks a lot in advance

CodePudding user response:

You are mixing async - await with callbacks, try to change your code like this:

exports.bulkCartUpdate = async (req, res) => {
    let userId = req.params.userId;
    let CartId = req.profile.CartId;
    let items = req.body;
  
    var promises = [];
    for (let i of items) {
      const productId = i.productId;
      const quantity = i.quantity;
  
      try {
        const product = await Product.findById(productId);
        if (product) {
          const obj = {
            productId,
            quantity,
            price: product.price,
            name: product.name,
            stock: product.inventory,
          };
          promises.push(obj);
        }
      } catch (err) {
        console.log(`Error fetching product with ID ${productId}`);
      }
    }
    console.log(promises);
  };  

CodePudding user response:

You probably want an array of promises for Promise.all(). You need to remove callbacks and await and then push it into an array.

exports.bulkCartUpdate = async (req, res) => {

  let userId = req.params.userId;
  let CartId = req.profile.CartId;
  let items = req.body;

  var promises = [];
  for (let i of items) {
    const productId = i.productId;
    const quantity = i.quantity;
    promises.push(Product.findById(productId).lean());
  }

  Promise.all(promises).then(async (products) => {
    // console.log(products);
  }).catch(e => console.error(e))
}

here is the reference.

  • Related