简体   繁体   English

将回应返回2个诺言

[英]Returning the responses to 2 promises

I am using Contenful for managing content and using the API with node.js to render the content. 我正在使用Contenful来管理内容,并使用带有node.js的API来呈现内容。 However, (and I suspect this question is probably applicable for anywhere 2 requests are being made and the combined result needs to be returned) but how do I return the data of 2 promises together? 但是,(并且我怀疑这个问题可能适用于正在发出2个请求并且需要返回合并结果的任何地方),但是我如何一起返回2个Promise的数据?

I have 2 collections, Page and News. 我有2个收藏集,分别是Page和News。

I want to return a specific page and all news, and I can do both of these separately, no problem at all. 我想返回特定的页面和所有新闻,并且我可以分别完成这两个操作,完全没有问题。

var pageData;
client.getEntry('Homepage')
.then(function (entry) {

  pageData = entry.fields;
  res.render('index', {
    pageData
  });
})

and

var pageData;
client.getEntries({'content_type':'news'})
.then(function (entries) {

  pageData = entries;
  res.render('index', {
    pageData
  });
})

however, what I'd like to get is something which resembles this: 但是,我想要得到的是类似于以下内容的东西:

// Get the page
...

// Get the news items
...

res.render('index', {
pageData,
news
});

How do I do this? 我该怎么做呢?

You can do the requests in parallel by starting them both and using Promise.all to wait for them both to finish: 您可以通过同时启动两个请求并使用Promise.all等待它们都完成来并行执行请求:

Promise.all([
    client.getEntry('Homepage'),
    client.getEntries({'content_type':'news'})
])
.then(([pageData, news]) => {
    // Use `pageData` and `news` here
})
.catch(error => {
    // One of them failed, handle/display error
});

Promise.all waits for all of the promises to be fulfilled and then fulfills its promise with those resolution values as an array in the same order as the entries in the array it receives (or rejects when one of the promises rejects, passing on the rejection reason). Promise.all等待所有promise都实现,然后将这些分辨率值作为一个数组以与接收到的数组中条目相同的顺序作为数组来实现其promise(或在其中一个promise拒绝时拒绝,继续拒绝原因)。

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

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