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

时间:2018-09-11 20:38:37

标签: javascript node.js promise

我正在尝试从承诺中获取价值。

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


}

所以我拥有的是一系列Promise对象,如下所示:

    Promise {
  { title: 'Work out why we can\'t run the GAX tests with parallelism',
  body: 'We\'ve had to disable parallelism in GAX tests, as otherwise the FakeScheduler tests hang, although only on Travis... but it\'s not clear why. At some point, we should investigate that...\n',
  labels: [ [Object] ] } }

例如,我将如何获得标题?

3 个答案:

答案 0 :(得分:2)

当您想使用等待的promises调用的结果时,仍在使用Promise.all变量来尝试访问值。 EG:

const results = await Promise.all(promises);


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

答案 1 :(得分:2)

这有助于了解诺言如何表现Promise.all

没有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)
})

使用await时,将返回通常在then内部检索的值,因此您需要将其存储在变量中并使用它。这样就得到:

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)

答案 2 :(得分:0)

您可以通过-

来访问标题
let promise = await Promise.all(promises);    
console.log(promise[0].title);