首页 > 解决方案 > 数组破坏时异步/等待

问题描述

我希望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而不是实际数据

标签: javascriptasynchronousasync-await

解决方案


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

推荐阅读