打破 Angularjs 中的承诺 [英] Break Out of then promises in Angularjs

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

问题描述

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

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.

我想找到一种更优雅的方式来打破 then 链.

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

推荐答案

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

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天全站免登陆