[英]Node.js handling response from http request
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. 我想在httprequest之外但在exports.post函数内部使用数据。 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: 如果要加入请求数据,可以在这种情况下使用Promises:
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
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.