Home > OS >  How can i get value from promise array?
How can i get value from promise array?

Time:12-17

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.

CodePudding user response:

Use Promise.all.

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