【问题标题】:Break Out of then promises in Angularjs在 Angularjs 中打破承诺
【发布时间】:2014-11-06 13:51:09
【问题描述】:

我正在尝试找到一种方法来打破 AngularJS 代码中的承诺链。显而易见的方法是返回一个对象,然后检查链中每个“then”函数的有效性。

我想找到一种更优雅的方式来打破当时的链条。

【问题讨论】:

    标签: angularjs break q angular-promise


    【解决方案1】:

    在 Angular 中,有可以注入指令、控制器等的 $q 服务,这是对 Kris Kowal 的 Q 的紧密实现。 所以在 then 函数内部而不是返回一个值或其他将链接到下一个“thenable”函数的东西,只需返回一个 $q.reject('reject reason');

    例子:

    angular.module('myQmodule',[])
    .controller('exController',['$q',function($q){
      //here we suppose that we have a promise-like function promiseFunction()
      promiseFunction().then(function(result1){
        //do the check we want in order to end chain
        if (endChainCheck) {
          return $q.reject('give a reason');
        }
        return;
      })
      .then(function(){
      //this will never be entered if we return the rejected $q
      })
      .catch(function(error){
       //this will be entered if we returned the rejected $q with error = 'give a reason'
      });
    }]);
    

    【讨论】:

      猜你喜欢
      • 2020-02-23
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      • 1970-01-01
      • 2019-03-27
      • 1970-01-01
      • 2015-10-07
      相关资源
      最近更新 更多