Search code examples
javascriptasynchronousasync-awaitpromisees6-promise

How can i get value from promise array?


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.


Solution

  • Use Promise.all.

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