【问题标题】:Be DRY with Angular promises in services在服务中使用 Angular 承诺保持干燥
【发布时间】:2013-08-29 12:25:34
【问题描述】:

当使用使用 xhr 而不是 $http 的第三方库时,在服务中使用 Promise 的正确方法是什么?

        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;
        }

像这样使用 $rootScope 看起来很难看,而且不像 Angular 那样,但是将范围作为参数传递也是如此。 有没有更好的方法来做到这一点?

【问题讨论】:

    标签: angularjs promise


    【解决方案1】:

    这似乎是$q.when() 的完美用途:

    将可能是值或(第 3 方)then-able 承诺的对象包装到 $q 承诺中。当您处理的对象可能是也可能不是 Promise 时,或者当 Promise 来自不可信的来源时,这很有用。

    $q.when() 返回一个$q 承诺,因此您的代码可以简化为:

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

    【讨论】:

    • 嗨,贾斯汀,感谢您的光临,实际上我试过了,但它不适用于范围:/
    猜你喜欢
    • 2014-06-26
    • 1970-01-01
    • 2023-03-08
    • 2011-08-18
    • 2015-08-12
    • 1970-01-01
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多