I have created a service that calls http/https links. I'm able to successfully call the http/https link, but i'm not able to store the output that the link returns. I understand this is quite tough due to the asynchronous operation. Please help if there is any way that I could store the retrieved data
Below is my code. I tried creating a global variable and then storing the retrieved data, but it dosen't work.
function apiCall(url, protocol) {
function externalApi(url, callback) {
try {
var https = $.require(protocol);
var request = https.request(url, function (response) {
var str = '';
var statusCode = response.statusCode;
var headers = response.headers;
response.on('data', function (data) {
str += data;
});
response.on('end', function () {
console.log("Data is " + str);
console.log("Status Code is " + statusCode);
console.log("Header is " + JSON.stringify(headers));
callback(str, statusCode);
});
});
request.on('error', function (e) {
console.log('Problem with request: ' + e.message);
console.log('Problem with request: ' + e);
});
request.end();
} catch (err) {
console.log("the error is" + err);
}
}
var status = function (data, statusCode) {
var callStatus = {};
if (statusCode == 200) {
callStatus.retrievedData = data;
callStatus.statusCode = statusCode;
callStatus.MESSAGE = "Successfully called";
}
console.log(callStatus);
};
externalApi(url, status);
}
The expected result would the function that returns the retrieved data or storing the retrieved data in some global variable. Right now I'm able to console log it. Please help
Edit : Tried storing the retreived data into a variable from callback
function apiCall(url, protocol) {
function externalApi(url, callback) {
var output = '';
..........
........
......
console.log("Header is " + JSON.stringify(headers));
output = callback(str, statusCode);
});
});
...................
....................
return output;
...............
...............
var result = externalApi(url, status);
console.log("The result is " + result);
}
But the result value is empty. This is due the asynchronous behavior. How to solve this. Ideally I would want the function apiCall to return the result. Something like below
var result = externalApi(url, status);
return result;
}