一尘不染

Angular的$ q.reject()与deferred.reject()

angularjs

我正在尝试获取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}

它提出了一些问题:

  1. $q.reject()和之间有什么区别deferred.reject()?什么时候使用每个?
  2. errorFnin deferred.promise.then(successFn, errorFn)catchFnin 之间有什么关系deferred.promise.catch(catchFn)
  3. 如果我有一堆嵌套的Promise发生错误,是否catch()总是会调用最外层的函数?如果其中一个嵌套的Promise也定义了catch函数怎么办?该捕获会阻止最外部的捕获执行吗?

谢谢。


阅读 278

收藏
2020-07-04

共1个答案

一尘不染

1)$q.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
    });
2020-07-04