Home > Software engineering >  How to wait for an object to be asynchronously edited?
How to wait for an object to be asynchronously edited?

Time:11-30

I have an array of items where I want to append an async value getProductMinQuantity.

The problem is that the render res.status(200)... is sent before item.order_quantity_minimum had been edited.

I thought that a map like below would create a new promise with the items updated.

newResult is a type Promise<any>[] | undefined, I cannot do .then .catch to then execut my res.status in it.

const getCart = async () => {
  
  ...

  let newResult = result.data?.line_items.physical_items.map(async (item: any) =>
    item.order_quantity_minimum = await getProductMinQuantity(item.product_id)
  )

  res.status(200).json({
    data: result.data ? normalizeCart(result.data) : null,
  })
}

Any thought how I can arrange that ?

CodePudding user response:

Classic question; you can't use await inside a synchronous array method (map, forEach, filter etc.). Instead, use a for...of loop.

let newResult = []

for(let item of result.data?.line_items.physical_items) {
  item.order_quantity_minimum = await getProductMinQuantity(item.product_id)
  newResult.push(item);
}

// Do something with newResult
  • Related