0

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?

michali
  • 3,230
  • 4
  • 18
  • 20

1 Answers1

0

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);
    }
   })
abdulbarik
  • 6,101
  • 5
  • 38
  • 59