我是Nodejs的新手,我还在学习如何解决它的异步方式。还有许多其他答案涵盖了在节点中使用来自http get请求的回调响应的结果,但是,我不想立即使用结果,而是将结果返回到不同的函数,并继续我收到的一个所有回复。
所以我有一个像http-request.js
var conf = require('./config.js');
var https = require("https");
exports.httpRequest = function (param1, param2) {
var url = "https://some.restapi.com/api/search/json?param1="+param1+"¶m2="+param2;
https.get(url, function(response) {
response.on('data', function (chunk) {
body += chunk;
});
response.on('end', function () {
json = JSON.parse(body);
for(var name in json.results){
val1 = json.results[name].property.prop.value1;
val2 = json.results[name].property.prop.value2;
var vals = val1 + "," + val2;
arr.push(vals);
}
//This would be the place I find I am suppose to use the result.
//But I cannot do this, instead, I need to return the array to another function
return arr;
});
});
}
主文件名为Demo.js
var arr1 = [];
var arr2 = [];
var arr3 = [];
var httpreq = require('./http-request.js');
arr1 = httpreq.httpRequest(param, key1);
arr2 = httpreq.httpRequest(param, key2);
arr3 = httpreq.httpRequest(param, key3);
我的问题是arr1 - arr3未定义,因为它们在收到响应之前被赋值。在尝试使用任何值之前,如何等待来自不同文件的所有响应?