michal zfania michal zfania - 1 month ago 5
Node.js Question

Nodejs http.get return body when request ends

I wrote this function:

_sendGetRequest : function (query) {
http.get({
host: elasticIp,
port: elasticPort,
path: "/logstash-2016.09.19/_search?source=" +
query
}, function (response) {
var body = '';
response.on('data', function (d) {
body += d;
});
response.on('end', function () {
//return body
});
});

}


I want _sendGetRequest to return response.body only when http request ends
How can I do that with/without promise?

Answer

It's running in asynchronous nature you can use callback or promise to get it done.

Here is example with callback

 _sendGetRequest: function(query,callback) {
     http.get({
       host: elasticIp,
       port: elasticPort,
       path: "/logstash-2016.09.19/_search?source=" +
         query
     }, function(response) {
       var body = '';
       response.on('data', function(d) {
         body += d;
       });
       response.on('end', function() {
         //return body
         callback(null,body);
       });
     });

   }

And call you function like this

_sendGetRequest(query,function(err,body){
    if(!err){
      console.log(body);
    }
   })