【问题标题】:How can i get value from promise array?我如何从承诺数组中获取价值?
【发布时间】:2021-12-16 14:00:17
【问题描述】:

我有一个包含 Promises 数组的代码

async function getResult(){
  ...
  //resultPromise  ==> it has promise in array Ex.[Promise { <pending> }, Promise { <pending> }]
  let finalResult = await resultPromise.map((result) => {
    //result has each promise from promise array
    result.then((obj) => {
      return obj.data
    })
  })
}

由此我想将obj.data 存储在变量finalResult 中。我该怎么做?

我尝试了以下方法

return resultPromise.map((result)=>{
    result.then((obj)=>{
      console.log(obj.data)
      return obj.data
    })
  })

resultPromise.map((result)=>{
    result.then((obj)=>{
      console.log(obj.data)
      return obj.data
    })
  })

我知道链接方式,但是我无法从中获得正确的值。

【问题讨论】:

  • 我不敢相信我找不到这个的副本...如果没有欺骗锤的人找到一个,请随时通知我。

标签: javascript asynchronous async-await promise es6-promise


【解决方案1】:

使用Promise.all

async function getResult(){
  ...  
  let finalResult = (await Promise.all(resultPromise)).map((obj) => obj.data);
  ...
}

【讨论】:

  • 谢谢我解决了。你的帮助对我帮助很大。祝你有美好的一天:)
猜你喜欢
  • 2018-05-16
  • 1970-01-01
  • 2019-04-26
  • 1970-01-01
  • 1970-01-01
  • 2020-11-02
  • 1970-01-01
  • 1970-01-01
  • 2017-05-29
相关资源
最近更新 更多