突破Angularjs的承诺

mit*_*1os 3 break angularjs q angular-promise

我试图找到一种方法来突破AngularJS代码中的承诺链.显而易见的方法是返回一个对象,然后检查链中每个"then"函数的有效性.

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

mit*_*1os 9

在角度方面,有一个$ q服务可以注入指令,控制器等,这是Kris Kowal的Q的紧密实现.所以在函数内部而不是返回一个值或其他链接到下一个的"可靠的"功能,只需返回一个 $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'
  });
}]);
Run Code Online (Sandbox Code Playgroud)