Search code examples
angularjsrestangularjs-scopeangularjs-serviceangularjs-http

AngularJS call callback function


I want to call a callback function but i can't get the data because my call is wrong.

I tried:

//function with callback
filterList: function(type, cb) {

 if (type == 'all') {
  var resource = infoboxApi.resource1().query();
 } else if (type == 'group') {
  var resource = infoboxApi.resource2().query();
 }

 resource.$promise.then(function(events) {
  var eventContainer = [];
  angular.forEach(events, function(event) {                  
   eventContainer.push({
    id: event.id,
    title: event.title
   })
  });
  cb(eventContainer);
 });

 return wrapSaveHandlers(resource);
 }



//call i tried
var newSources = [];
filterList('all', function(result) {
 newSources = result;
});

I want newSources to contain the data but it's empty if i call it like this.

Anyone know how to call it the right way?


Solution

  • Avoid using callbacks in promise-based APIs. Instead use return statements:

     //function without callback
     filterList: function(type) {
         var resource;       
         if (type == 'all') {
             resource = infoboxApi.resource1().query();
         } else if (type == 'group') {
             resource = infoboxApi.resource2().query();
         };
    
         //RETURN the promise
         return resource.$promise.then(function(events) {
             var eventContainer = [];
             angular.forEach(events, function(event) {                  
                 eventContainer.push({
                     id: event.id,
                     title: event.title
                 })
             });
             //RETURN the data
             return eventContainer;
         });
     }
    

    And extract the data from the returned promise:

    var newSources = [];
    filterList('all').then(function(result) {
        newSources = result;
    });
    

    The .then method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback (unless that value is a promise, in which case it is resolved with the value which is resolved in that promise using promise chaining.