With the request
library, is there a way to use promises to simplify this callback?
var context = {};
request.get({
url: someURL,
}, function(err, response, body) {
context.one = JSON.parse(body);
request.get({
url: anotherURL,
}, function(err, response, body) {
context.two = JSON.parse(body);
// render page
res.render('pages/myPage');
});
});
Best Answer
Here's a solution using the Bluebird promises library. This serializes the two requests and accumulates the results in the
context
object and rolls up error handling all to one place:And, if you have multiple URLs, you can use some of Bluebirds other features like
Promise.map()
to iterate an array of URLs:Or, you could create a helper function to do this for you: