0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

ty for this code but if i look into newSources it's still empty after the call of filterList
Use standard debugging to techniques to determine where the data is being lost. Insert console.log statements. Review the network tab in the Developer Console.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.