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

los*_*rje 64 javascript promise 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}
Run Code Online (Sandbox Code Playgroud)

它提出了几个问题:

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

谢谢.

dus*_*yle 95

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
    });
Run Code Online (Sandbox Code Playgroud)

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
    });
Run Code Online (Sandbox Code Playgroud)


Day*_*eon 5

好的,这是我对承诺的看法.

  1. $q.reject(reason)返回一个被拒绝的promise,其原因是作为参数传递并且deferred.拒绝拒绝现有的否定其过程是否已完成.

  2. errorFn当一个承诺被拒绝时它会被启动,它的参数就是它被拒绝的原因.如果未正确处理承诺流程中的错误导致承诺提升和异常而不被拒绝或履行,则调用Catch.

  3. 你没有嵌套的promises,你应该有链接的promises,在这种情况下,如果没有指定其他块来处理它,最新的catch块应该先捕获它之前的所有内容.