![](/img/trans.png)
[英]AngularJS deferred.reject not working but $q.reject working
[英]Angular's $q.reject() vs deferred.reject()
我正在尝试处理Angular $q
服务及其相关对象和API。 当我在控制台中查看对象时,我看到:
var deferred = $q.defer()
...(and then from console inspection)...
$q: Object {defer: function, reject: function, when: function, all: function}
deferred: Object {resolve: function, reject: function, notify: function, promise: Object}
deferred.promise: Object {then: function, catch: function, finally: function}
它提出了几个问题:
$q.reject()
和deferred.reject()
之间有什么区别? 什么时候使用? errorFn
在deferred.promise.then(successFn, errorFn)
和catchFn
在deferred.promise.catch(catchFn)
catch()
函数吗? 如果其中一个嵌套的promises也定义了catch函数怎么办? 这种捕获会阻止最外层的捕获吗? 谢谢。
1) $q.reject()
是创建延迟的快捷方式,然后立即拒绝它; 如果我无法处理错误,我经常在errorFn中使用它。
2)没有, promise.catch(errorFn)
只是promise.catch(errorFn)
promise.then(null, errorFn)
语法糖,就像$http
服务的成功和错误方法一样,所以你可以编写如下代码:
promise.
then(function(result){
// handle success
return result;
}, function errorHandler1(error){
// handle error, exactly as if this was a separate catch in the chain.
}).catch(function errorHandler2(error){
// handle errors from errorHandler1
});
3)这正是$ q.reject可以派上用场的地方:
promise.
catch(function(error){
//Decide you can't handle the error
return $q.reject(error); //This forwards the error to the next error handler;
}).catch(function(error){
// Here you may handle the error or reject it again.
return 'An error occurred';
//Now other errorFn in the promise chain won't be called,
// but the successFn calls will.
}).catch(function(error){
// This will never be called because the previous catch handles all errors.
}).then(function(result){
//This will always be called with either the result of promise if it was successful, or
//'An error occured' if it wasn't
});
好的,这是我对承诺的看法。
$q.reject(reason)
返回一个被拒绝的promise,其原因是作为参数和deferred传递的。 拒绝拒绝现有的否定其过程是否已完成。
当promise被拒绝并且其参数是被拒绝的原因时,将启动errorFn
。 如果未正确处理承诺流程中的错误导致承诺提升和异常而不被拒绝或履行,则调用Catch。
你没有嵌套的promises,你应该有链接的promises,在这种情况下,如果没有指定其他块来处理它,最新的catch块应该先捕获它之前的所有内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.