1

I have a code which has an array of 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
    })
  })
}

From this I want to get obj.data stored in the variable finalResult. How can I do that?

I tried below ways

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

or

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

I know the chaining way but, I couldn't get the correct value from it.

Kaiido
  • 123,334
  • 13
  • 219
  • 285
Boris Park
  • 105
  • 1
  • 10
  • I can't believe I can't find a duplicate for this... If someone without a dupe-hammer finds one, feel free to notify me. – Kaiido Dec 16 '21 at 06:03

1 Answers1

2

Use Promise.all.

async function getResult(){
  ...  
  let finalResult = (await Promise.all(resultPromise)).map((obj) => obj.data);
  ...
}
zmag
  • 7,825
  • 12
  • 32
  • 42