我正在尝试处理 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()
有什么区别?什么时候使用它们?deferred.promise.then(successFn, errorFn)
中的errorFn
和deferred 中的
?catchFn
是什么关系。 promise.catch(catchFn)- 如果我有一堆嵌套的 promise 并且发生错误,最外层的
catch()
函数是否总是被调用?如果其中一个嵌套的 promise 也定义了 catch 函数怎么办?该 catch 会阻止最外层的 catch 执行吗?
谢谢。
最佳答案
1) $q.reject()
是创建deferred然后立即reject的快捷方式;如果我无法处理错误,我经常在 errorFn 中使用它。
2) 没什么,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
});
关于javascript - Angular 的 $q.reject() 与 deferred.reject(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24443733/