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

查看:89
本文介绍了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放入第一个然后,第二个然后将被解析,并且将调用其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 docs传播的唯一方法拒绝是返回 $ 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 中抛出异常来完成,但是它将异常跟踪写入控制台,这是不好的。

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中,您可以尝试修复错误状态并解决它以某种方式承诺。

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天全站免登陆