Randheer Singh Chouhan Randheer Singh Chouhan - 3 months ago 8
AngularJS Question

how to handle response in angularjs?

so here is the code snippet which is fetching data from parse:

var schooolId = 111;

var query = new Parse.Query("Schools");

query.equalTo("objectId", schooolId);

query.find({
success: function (results) {

console.log('in success');
$scope.funnelId = results[0].get("funnelId");

},
error: function (error) {

}

});

console.log('after function >> ' + $scope.funnelId);


now the output comes it print first "after function >>' and then 'in success' by this way it dosn't put value in '$scope.funnelId', we need to wait for response and then execute the rest.

this should response like this :
output :
"in success"
then
"after function >>"

by this way this will put value in : $scope.funnelId

Please suggest.

Answer

Promises would solve the issue.

var query = new Parse.Query("Schools");

query.equalTo("objectId", schooolId);
var defer = $q.defer();
query.find({
success: function (results) {

    console.log('in success');
 defer.resolve(results[0].get("funnelId"));
},
error: function (error) {
  defer.reject(error);
}

});

defer.promise.then(function(funnelid){
  console.log('after function >> ' + funnelid);
})

The problem is that the asynchronous call to parse has not returned before you hit the console.log. With promises you can control when you console.log (or do some logic on the returned values)