I have some code as follows:
exports.post = function(request, response) {
var httpRequest = require('request');
var uri = "url..";
httpRequest(uri, function(err, responseHeaders, bodyResponse) {
var data = JSON.parse(bodyResponse);
});
}
I want to use the data outside the httprequest, but inside the exports.post function. In all the examples I have seen, everyone uses the body for logging, but I want to use the data.
If you want to join requests data, you could use Promises in this case:
function joinData() {
var httpRequest = require('request');
var url1 = 'http://echo.jsontest.com/request/first';
var url2 = 'http://echo.jsontest.com/request/second';
var promisedRequest = function (uri) {
return new Promise(function (resolve, reject) {
httpRequest(uri, function (err, responseHeaders, bodyResponse) {
var data = JSON.parse(bodyResponse);
resolve(data);
});
});
}
// both requests at the same time
Promise.all([promisedRequest(url1), promisedRequest(url2)])
.then(function (responsesArray) {
console.log(responsesArray); // <- your responses here
});
}
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.