Gepsens
Gepsens

Reputation: 673

Be DRY with Angular promises in services

What is the right way to use promises in services, when using a third party library that uses xhr and not $http ?

        getSomething: function(user, repo) {
            var deferred = $q.defer();
        client.doSomething().promise().then(function(result) {
                $rootScope.$apply(function() {
                    deferred.resolve(result);
                });
            }, function(err) {  
                $rootScope.$apply(function() {
                    deferred.reject(err);
                });
            });
            return deferred.promise;
        }

Using the $rootScope like that seems ugly and not Angular-ish, but so would passing the scope as a parameter. Is there any better way to do this ?

Upvotes: 0

Views: 255

Answers (1)

Justin Lovero
Justin Lovero

Reputation: 405

This appears to be the perfect use for $q.when():

Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.

$q.when() returns a $q promise, so your code can be simplified to:

getSomething: function(user, repo) {
    return $q.when(client.doSomething().promise());
}

Upvotes: 0

Related Questions