How to set new propertie or push to array with async and await with in callback function?


#1

This is my script, I don’t know why when I use asysc await with rawCollection when I get data inside loop and then I set new properties (poTmp) inside I get data but after i set new properties I console outside it do not set new prop why?

let items = await Items.rawCollection()
    .aggregate([
      {
        $match: match,
      },
    ])
    .toArray()
  
  items.forEach(async item => {
    let po = await PurchaseOrderDetails.rawCollection()
      .aggregate([
        {
          $match: {
            itemId: item._id,
            tranDate: { $lte: tDate },
          },
        },
        {
          $group: {
            _id: '$itemId',
            itemDoc: { $last: item },
            onHandPO: { $sum: '$qtyBase' },
          },
        },
        {
          $group: {
            _id: '$itemId',
            itemDoc: { $last: '$itemDoc' },
            lastOnHandPO: { $last: '$onHandPO' },
          },
        },
      ])
      .toArray()
    //==================
    //set new properties
    //==================
    item.poTmp = po[0]

  })
  console.log(items)
  return items


#2

Are you asking why console.log(items) does not include item.poTmp?

Taking out the aggregations, your code looks like this:

// ...
items.forEach(async item => {
  // ...
  item.poTmp = po[0]
})
console.log(items)
return items

As you can see, you are not modifying items at all. You are just modifying an intermediate result.


#3

Yes I want to set new prop intermediately but the result not wait.


#4

You’re running async code. That’s just the same as any asynchronous code - the code which follows runs before the asynchronous section finishes. However, as I said originally, you’re reporting on items, but you’re not changing that inside the async section. What are you expecting to happen?


#5

I see I will try thank