摆脱然后Angularjs承诺 [英] Break Out of then promises in Angularjs

查看:167
本文介绍了摆脱然后Angularjs承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种方法,打破了在AngularJS code诺言链。最明显的办法是返回一个对象,然后检查的有效性是在链的每一个,那么功能。

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.

推荐答案

在棱角分明,有可以在指令注入了$ Q服务,控制器等,也就是克里斯·科瓦尔的Q的接近implentation
所以,那么里面的函数,而不是返回将被链接到下一个thenable功能的值或别的东西,只返回一个 $ q.reject(拒绝的理由');

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

例如:

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

这篇关于摆脱然后Angularjs承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆