简体   繁体   中英

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?

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]);

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)

You can get access to the title as-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM