Steffany Brown
Steffany Brown

Reputation: 13

retrieving values from resolved Promise object

I am trying to get the values out of an array of promises.

  async function retrieveIssues() {
  
  let rawdata = fs.readFileSync(argv.i);
  let issues = JSON.parse(rawdata);

  const issuesArray = issues.Issues;

  const promises = issuesArray.map(issue => getIssueInfo(issue));

  await Promise.all(promises);


  // promises is now array of current issue information
  console.log(promises)
  console.log(promises[0])


}

So what I have is an array of Promise objects that look like this:

    Promise {
  { title: 'Work',
  body: 'We\'ve had...\n',
  labels: [ [Object] ] } }

So how would I get access to the title, for example?

Upvotes: 1

Views: 55

Answers (3)

Herohtar
Herohtar

Reputation: 5613

It helps to understand how promises behave to know what to do with Promise.all.

Without async/await, your code would look like this:

Promise.all(promises).then(results => {
  // results is now an array of current issue information
  console.log(results)
  console.log(results[0])
  console.log(results[0].title)
})

When you use await, the value that would normally be retrieved inside the then gets returned, so you need to store it in a variable and use that. Thus you get:

let results = await Promises.all(promises)
// results is now an array of current issue information
console.log(results)
console.log(results[0])
console.log(results[0].title)

Upvotes: 2

Ashish Patel
Ashish Patel

Reputation: 367

You can get access to the title as-

let promise = await Promise.all(promises);    
console.log(promise[0].title); 

Upvotes: 0

CRice
CRice

Reputation: 32146

You are still using the promises variable to try to access the values, when you want to use the result of your awaited Promise.all call instead. EG:

const results = await Promise.all(promises);


// promises is now array of current issue information
console.log(results);
console.log(results[0]);

Upvotes: 2

Related Questions