【问题标题】:How to wait for an object to be asynchronously edited?如何等待对象被异步编辑?
【发布时间】:2022-01-06 23:09:34
【问题描述】:

我有一个 arrayitems,我想在其中附加一个异步值 getProductMinQuantity

问题是渲染 res.status(200)... 在 item.order_quantity_minimum 被编辑之前发送。

我认为像下面这样的地图会创建一个更新项目的新承诺。

newResultPromise<any>[] | undefined 类型,我不能在其中执行.then .catch 然后在其中执行我的res.status

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,
  })
}

有没有想过我该如何安排?

【问题讨论】:

  • 但是如果你以后不使用它,为什么要构建一个newResult 数组呢?

标签: javascript typescript asynchronous async-await promise


【解决方案1】:

经典问题;您不能在同步数组方法(map、forEach、filter 等)中使用await。相反,请使用 for...of 循环。

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

【讨论】:

  • 它告诉我 result.data?.line_items.physical_items 可能有一个值 'undefined'
  • 确实,好吧,加if(result.data?.line_items.physical_items)
  • 谢谢,我什至不需要newResultfor...of,我的result.data?.line_items.physical_items 在发送我的回复之前已经过很好的编辑。
  • 是的,因此我在上面的评论询问您为什么要构建 newResult 数组而不是之后使用它。实际上,每个item 都直接在physical_items 中通过引用进行修改
  • 在我之前使用它的方式中,如前所述,我试图阅读并用它做一些事情,但没有成功。我没有写下我尝试过的所有内容,因为我知道我的做法是错误的。但不知道for...of。我想我现在会使用更多for...of :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-02
  • 2023-03-04
  • 2020-12-17
  • 1970-01-01
  • 2021-11-18
  • 2023-03-12
相关资源
最近更新 更多