Lukáš Unzeitig Lukáš Unzeitig - 3 months ago 19
HTTP Question

Wait till the http.get will return object

How i can wait, till http.get will return object ??

getData: function(){
let obj = false;
http.get("http://...")
.accept("application/json")
.end(function(err,res){
if(err==null && res.ok){
let js = JSON.stringify(res.body);
obj = JSON.parse(js);
}
})
return obj;
},


this function i am calling
var obj = getData;
but i am still getting false, when i print the values, first its return false, and then object is assigned, so how wait till the object is assigned and then return object ??

Answer

The easiest method would be to use a fallback function. You can use a promise but that requires extra:

Change the function to accept a callback function, then call that function when the get call has returned:

getData: function(cb){
  let obj = false;
  http.get("http://...")
    .accept("application/json")
    .end(function(err,res){
      if(err==null && res.ok){
        let js = JSON.stringify(res.body);
        obj = JSON.parse(js);

        if (cb)
          cb(obj);
      }
    });
},

then call it with:

getData(function(obj){  
    // do something here with the returned object.
});

Asyncronous programming, which http.get is, uses events in the form of callbacks - and promises. So wait for http.get to return which is the event, then proceed once it returns.

Comments