Break Out of then promises in Angularjs

孤街醉人 提交于 2019-12-23 20:04:09

问题


I am trying to find a way to break out of a promise chain in AngularJS code. The obvious way was to return an object and then check is validity in every "then" function in the chain.

I would like to find a more elegant way of breaking out of a then chain.


回答1:


In angular, there is the $q service that can be injected in directives, controllers etc, that is a close implentation of Kris Kowal's Q. So inside of then function instead of returning a value or something else that would be chained to the next "thenable" function, just return a $q.reject('reject reason');

Example:

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'
  });
}]);


来源:https://stackoverflow.com/questions/26781152/break-out-of-then-promises-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!