首页 > 解决方案 > 异步调用在 JS 的这个块内不起作用

问题描述

我正在尝试在对象数组中使用 forEach 并根据以下条件发送请求并获取该响应以在另一个调用中使用。这是代码:

  products.forEach(product => {
    if (
      product.type === 'shows' &&
      product.isSoldOut &&
      product.otherData
    ) {
      delete product.brand.brandId
      product.brand.isTop = true
      const res = apiService.create(product.brand)
      console.log(res)
    }
  })

当我在这里添加等待时const res = await apiService.create(product.brand),它也会显示警告。在这种情况下如何使用异步等待,或者有其他方法可以解决这个问题吗?

标签: javascriptarraysecmascript-6async-await

解决方案


您需要将回调标记为异步以允许您使用等待。他们总是必须成对出现。

例如

products.forEach(async (product) => {
    if (
      product.type === 'shows' &&
      product.isSoldOut &&
      product.otherData
    ) {
      delete product.brand.brandId
      product.brand.isTop = true
      const res = apiService.create(product.brand)
      console.log(res)
    }
  })

推荐阅读