0

I had the following code in my project and I was hoping it worked.

var retrieveUpdates = function (hash) {
    myFunction(data)
      .then(function(filters){
        return Restangular.all('retrieveUpdates').post({ filters });
    });
};

But of course this fails because a return is happening before the then. I can "fix" it but it seems to be ugly (especially when this scenario is all over the place).

var retrieveUpdates = function (hash) {
    var defer = $q.defer();
    myFunction(data)
      .then(function(filters){
        Restangular.all('retrieveUpdates').post({ filters }).then(defer.resolve, defer.reject);
      });
    return defer.promise;
};

Is there a cleaner way to do this?

Jackie
  • 21,969
  • 32
  • 147
  • 289
  • Why can't you just stick with what you have in the first place. It returns a promise so just chain off it for resolution callbacks? You can even do this in the service if you want and update a scope from there. – David Barker Dec 11 '14 at 17:38
  • Related [What is the deferred anti-pattern and how do I avoid it?](http://stackoverflow.com/questions/23803743/what-is-the-deferred-antipattern-and-how-do-i-avoid-it) – Benjamin Gruenbaum Dec 12 '14 at 01:08

3 Answers3

3

You aren't returning anything in your first example, just return myFunction

var retrieveUpdates = function (hash) {
    return myFunction(data)
      .then(function(filters){
        return Restangular.all('retrieveUpdates').post({ filters });
    });
};
John
  • 6,503
  • 3
  • 37
  • 58
0
var retrieveUpdates = function (hash) {
    return $q(function(resolve, reject){
        myFunction(data)
          .then(function(filters){
              return Restangular.all('retrieveUpdates').post({ filters }).then(resolve, reject);
           });
    });     
};
ppoliani
  • 4,792
  • 3
  • 34
  • 62
0

Have you tried

var retrieveUpdates = function (hash) {
    return myFunction(data)
      .then(function(filters){
         return Restangular.all('retrieveUpdates').post({ filters });
      });
 };

that is the common patter for promises, a promise, always returns a promise

Ricardo Garza V.
  • 899
  • 1
  • 11
  • 26