Angular 的 $q.reject() 与 deferred.reject() [英] Angular's $q.reject() vs deferred.reject()
问题描述
我正在尝试处理 Angular $q
服务及其相关对象和 API.当我查看控制台中的对象时,我看到:
I'm trying to get a handle on the Angular $q
service and its related objects and APIs. When I look at the objects in my console I see:
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()
有什么区别?什么时候使用?deferred.promise.then(successFn, errorFn)
中的errorFn
和deferred中的
?catchFn
有什么关系.promise.catch(catchFn)- 如果我有一堆嵌套的 promise 并且发生错误,最外层的
catch()
函数会一直被调用吗?如果嵌套的 promise 之一也定义了 catch 函数怎么办?该 catch 会阻止最外层的 catch 执行吗?
- What's the difference between
$q.reject()
anddeferred.reject()
? When to use each? - What's the relationship between the
errorFn
indeferred.promise.then(successFn, errorFn)
and thecatchFn
indeferred.promise.catch(catchFn)
? - If I have a bunch of nested promises and an error occurs, will the outermost
catch()
function always be called? What if one of the nested promises also has a catch function defined? Will that catch prevent the outermost catch from executing?
谢谢.
推荐答案
1) $q.reject()
是创建延迟然后立即拒绝它的快捷方式;如果我无法处理错误,我经常在 errorFn 中使用它.
1) $q.reject()
is a shortcut to create a deferred and then reject it immediately; I often use this in an errorFn if I can't handle the error.
2) 没什么,promise.catch(errorFn)
只是promise.then(null, errorFn)
的语法糖,就像$http
服务,因此您可以编写如下代码:
2) Nothing, promise.catch(errorFn)
is just syntactic sugar for promise.then(null, errorFn)
, just like the success and error methods of the $http
service, so you can write code like the following:
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 可以派上用场的地方:
3) This is exactly where $q.reject can come in handy:
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
});
这篇关于Angular 的 $q.reject() 与 deferred.reject()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!