Boris Park
Boris Park

Reputation: 105

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.

Upvotes: 1

Views: 1835

Answers (1)

zmag
zmag

Reputation: 8261

Use Promise.all.

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

Upvotes: 2

Related Questions