I am new to Nodejs, and am still learning how to work around it's asynchronous ways. There are many other answers that cover using results of a callback response from an http get request in node, however, I do not want to use the results right away, but rather return the results to a different function, and continue one I have received all responses.
So I have a file like 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;
});
});
}
And the main file called 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);
My problem is that arr1 - arr3 are undefined, because they are assigned values before the response is received. How can I wait for all the responses from a different file before I attempt to use any values?