简体   繁体   English

从已解决的 Promise 对象中检索值

[英]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 对象,如下所示:

    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.当您想使用等待的Promise.all调用的结果时,您仍在使用promises变量来尝试访问这些值。 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 .了解Promise.all行为方式有助于了解如何处理Promise.all

Without async/await , your code would look like this:如果没有async/await ,您的代码将如下所示:

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.当您使用await ,通常会在then检索的值被返回,因此您需要将其存储在一个变量中并使用它。 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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