我正在尝试获取Angular $q服务及其相关对象和API 的句柄。当我查看控制台中的对象时,我看到:
$q
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()
谢谢。
1)$q.reject()是创建延迟然后立即拒绝的快捷方式;如果我无法处理错误,我经常在errorFn中使用它。
2)没什么,promise.catch(errorFn)仅仅是服务的语法糖promise.then(null, errorFn),就像服务的成功和错误方法一样$http,因此您可以编写如下代码:
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 });