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

标签 javascript angularjs promise

我正在尝试处理 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. deferred.promise.then(successFn,​​ errorFn) 中的errorFndeferred 中的catchFn 是什么关系。 promise.catch(catchFn)?
  3. 如果我有一堆嵌套的 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/

相关文章:

javascript - 在一组中用空格将数字字符串分隔为 4(不是那么容易实现)

javascript - 随机生成低多边形地形

javascript - 如何处理项目点击从 ng-repeat 生成的列表并加载下一页

angularjs - 将表单设置为原始状态时消除字段错误

javascript - 如何循环 3 个 setInterval 函数,但将它们链接为 promise ,以便解决并继续?

javascript - 带双点的 Angular 电子邮件验证

javascript - 正则表达式: Match word or Phrase

javascript - Angular 形式广泛验证(非特定领域)

javascript - ES6 promise : Promise status not as I expect

javascript - 在 Protractor 中传播 promise