Today I am doing this request to Linode API.
var options = {
hostname: 'api.linode.com',
path: '',
port: 443,
method: 'GET'
}
var req = https.request(options, function(response) {
response.setEncoding('utf8');
response.on('data', function(d) {
body = JSON.parse(d.toString());
});
response.on('end', function() {
console.log(body);
});
}).end();
The output is working as expected on this example.
However, I need to put the response into a variable, and not log it to console.
var body = '';
var req = https.request(options, function(response) {
response.setEncoding('utf8');
response.on('data', function(d) {
body = JSON.parse(d.toString());
});
}).end();
console.log(body);
return body;
Running the above code, the answer is always empty, since looks like the console.log()
function or return
clause are not waiting for end of the request.
I resolved the problem using the setTimeout( function() { console.log(body); }, 2000 )
function, but to be honest can't see it as an effective solution, since the timeout will be different on each request.
Other solution I tried was while (!req.finished) {} console.log(body);
, but it is not working as expected too.
Finally, I tried to add this:
response.on('end', function() {
return body;
});
But no success as well :(
That said, do you have any suggestions to make this function wait for request timeout before return the value of the body
variable?