javascript - 数组破坏时异步/等待
问题描述
我希望Promise.all
在实际进行数组破坏之前解析内部的数据:
const function = async (one, two) => {
const [_one, _two] = await Promise.all([
one.map(translate), // translate is async
two.map(translate),
])
console.log(_one, _two)
}
const translate = async (data) => getTranslation(data) // getTranslation is async, an API call
现在,console.log
给我Promise
而不是实际数据
解决方案
one.map(translate)
返回一个承诺数组。您必须使用Promise.all
将其转换为Promise。
one // Element[]
one.map(translate) // Promise<Element>[]
Promise.all(one.map(translate)) // Promise<Element[]>
总之,您必须使用Promise.all
两次:
const function = async (one, two) => {
const [_one, _two] = await Promise.all([
Promise.all(one.map(translate)), // <<
Promise.all(two.map(translate)), // <<
])
console.log(_one, _two)
}
推荐阅读
- android - 用于照片堆栈的 Android 图标生成器
- c++ - 为什么我的 Go 解决方案给出的结果与 C++ 不同?
- bash - printf 在执行“printf H%03s 3A”时添加尾随空格而不是 0
- azure - Azure DevOps REST API:有没有办法通过 REST API 运行 WIQL 来显示工作项的所有字段
- python - h2o.weights() 返回无
- node.js - 如何解决错误:在 kubernetes 上运行时找不到模块“react-dev-utils/chalk”?
- ios - 动态处理 UICollectionViewCell 元素内的背景和前景色
- matplotlib - 在 Cartopy 中剪掉圆形 set_boundary 之外的 pcolormesh
- amazon-dynamodb - 从与来自 DynamoDB 的日期连接的字符串中搜索与日期相关的数据
- python - Python中的家庭作业IF语句