简体   繁体   中英

Returning the responses to 2 promises

I am using Contenful for managing content and using the API with node.js to render the content. 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?

I have 2 collections, Page and 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([
    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).

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