javascript - 异步调用在 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)
,它也会显示警告。在这种情况下如何使用异步等待,或者有其他方法可以解决这个问题吗?
解决方案
您需要将回调标记为异步以允许您使用等待。他们总是必须成对出现。
例如
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)
}
})
推荐阅读
- php - 如何使用 PHP 按 SKU 获取 Square Inventory?
- javascript - 内部方法 [[GetOwnProperty]]
- c# - 从 System.Security.Cryptography 获取相同的加密字符串
- mongodb - 大数据仓库的非关系型数据库设计
- swift - 在 UIView 内播放视频剪辑到视图边界
- python - 如何从 Python 中的列表中获取特定值
- haskell - 为什么静态箭头泛化箭头?
- javascript - 放置复选标记时将文本复制到不同的文本区域
- json - Scala - 如何使用 json-path 拆分所有 List Json 节点列表
- kotlin - 访问数组内的变量 [Kotlin]