Angularjs 承诺拒绝链接 [英] Angularjs promise rejection chaining

查看:24
本文介绍了Angularjs 承诺拒绝链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建链式承诺:

var deferred = $q.defer();
$timeout(function() {
    deferred.reject({result: 'errror'});
}, 3000);
deferred.promise.then(angular.noop, function errorHandler(result) {
    //some actions
    return result;
}).then(function successCallback(result) {
    console.log('what do I do here?');
    return result;
}, function errorCallback(result) {
   $scope.result= result;
   return result;
});

如果我将 errorCallback 放入第一个 then,第二个 then 将被解析,并且它的 successCallback 将被调用.但是如果我删除 errorHandler 那么第二个承诺将被拒绝.

If I put an errorCallback into the first then, the second then will be resolved and its successCallback will be called . But if I remove errorHandler then second promise will be rejected.

根据 Angular JS 文档,传播拒绝的唯一方法是返回 $q.reject(); 并且它看起来并不明显,特别是因为我必须注入 $q服务,即使不需要;

According to Angular JS docs the only way to propagate rejection is to return $q.reject(); and it looks not obvious, especially because I have to inject $q service even if it is not needed;

也可以通过在errorHandler中抛出异常来完成,但是将异常trace写到console,不好.

It can also be done by throwing an exception in errorHandler, but it writes exception trace to console, it is not good.

是否有另一种选择以清晰的方式执行此操作?原因是什么?为什么要这样做?在哪种情况下,当前行为可能有用?

Is there another option to do this in a clear way? And what is the reason? Why it is done? In which case, the current behavior can be useful?

推荐答案

以及这样做的原因是什么.在哪种情况下,当前行为可能有用?

And what the reason why it is done. In which case, the current behavior can be useful?

当在 errorHandler 中尝试修复错误状态并以某种方式解决 promise 时,它​​会很有用.

It can be useful when in errorHandler you could try to repair error state and resolve promise somehow.

var retriesCount = 0;

function doWork()
{
    return $http.post('url')
        .then(function(response){
            // check success-property of returned data
            if(response.data.success)
                // just unwrap data from response, may be do some other manipulations
                return response.data;
            else
                // reject with error
                return $q.reject('some error occured');
        })
        .catch(function(reason){
            if(retriesCount++ < 3)
                // some error, let me try to recover myself once again
                return doWork();
            else
                // mission failed... finally reject
                return $q.reject(reason);
        });
}


doWork().then(console.log, console.error);

这篇关于Angularjs 承诺拒绝链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆