Catfish Catfish - 2 months ago 30
Javascript Question

Angular $promise without using defer

Everything on the net about promises these days says don't use defer when using promises except docs/examples on angular.js.

What is the proper way to return the value of an angular.js $promise without using defer?

Here's what I currently have:

function foo() {
var deferred = $q.defer();
userService.findProgramsByUser({personId: personId}).$promise
.then(function (programs) {
deferred.resolve(programs);
});
return deferred.promise;
}


If i was using the node Q library I would do this:

function foo() {
return Q.promise(function(resolve, reject) {
userService.findProgramsByUser({personId: personId})
.then(function (programs) {
resolve(programs);
});
}
}


How can I do something similar with an angular promise without having to use defer?

Answer

Since userService.findProgramsByUser() already has a promise property, just return that

function foo() {          
  return userService.findProgramsByUser({personId: personId}).$promise
     .then(function (programs) {
          return programs;
     }, function(){
        // handle errors
     });        
}
Comments