当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > AngularJS 中的Promise --- $q服务详解

AngularJS 中的Promise --- $q服务详解

2018年05月10日  | 移动技术网IT编程  | 我要评论
先说说什么是promise,什么是$q吧。promise是一种异步处理模式,有很多的实现方式,比如著名的kris kwal's q还有jquery的deffered。 什

先说说什么是promise,什么是$q吧。promise是一种异步处理模式,有很多的实现方式,比如著名的kris kwal's q还有jquery的deffered。

什么是promise

以前了解过ajax的都能体会到回调的痛苦,同步的代码很容易调试,但是异步回调的代码,会让开发者陷入泥潭,无法跟踪,比如:

funa(arg1,arg2,function(){
  funcb(arg1,arg2,function(){
    funcc(arg1,arg2,function(){
       xxxx....
    })
  })  
})

本身嵌套就已经很不容易理解了,加上不知何时才触发回调,这就相当于雪上加霜了。

但是有了promise这种规范,它能帮助开发者用同步的方式,编写异步的代码,比如在angularjs中可以使用这种方式:

deferabc.resolve(xxx)
.then(funcsuccess(){},funcerror(){},funcnotify(){});

当resolve内的对象成功执行,就会触发funcsuccess,如果失败就会触发funcerror。有点类似

deferabc.resolve(function(){
  sunccess:funcsuccess,
  error:funcerror,
  notify:funcnotify
})

再说的直白点,promise就是一种对执行结果不确定的一种预先定义,如果成功,就xxxx;如果失败,就xxxx,就像事先给出了一些承诺。

比如,小白在上学时很懒,平时总让舍友带饭,并且事先跟他说好了,如果有韭菜鸡蛋就买这个菜,否则就买西红柿炒鸡蛋;无论买到买不到都要记得带包烟。

小白让舍友带饭()
.then(韭菜鸡蛋,西红柿炒鸡蛋)
.finally(带包烟)

$q服务

q服务是angularjs中自己封装实现的一种promise实现,相对与kris kwal's q要轻量级的多。
先介绍一下$q常用的几个方法:

defer() 创建一个deferred对象,这个对象可以执行几个常用的方法,比如resolve,reject,notify等
all() 传入promise的数组,批量执行,返回一个promise对象
when() 传入一个不确定的参数,如果符合promise标准,就返回一个promise对象。

在promise中,定义了三种状态:等待状态,完成状态,拒绝状态。

关于状态有几个规定:

1 状态的变更是不可逆的
2 等待状态可以变成完成或者拒绝

defer()方法

在$q中,可以使用resolve方法,变成完成状态;使用reject方法,变成拒绝状态。

下面看看 $q的简单使用:

<html ng-app="myapp">
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script>
</head>
<body>
  <div ng-controller="myctrl">
    {{test}}
  </div>
  <script type="text/javascript">
     var myappmodule = angular.module("myapp",[]);
     myappmodule.controller("myctrl",["$scope","$q",function($scope, $ q ){
      $scope.test = 1;//这个只是用来测试angularjs是否正常的,没其他的作用

      var defer1 = $q.defer();
      var promise1 = defer1.promise;

      promise1
      .then(function(value){
        console.log("in promise1 ---- success");
        console.log(value);
      },function(value){
        console.log("in promise1 ---- error");
        console.log(value);
      },function(value){
        console.log("in promise1 ---- notify");
        console.log(value);
      })
      .catch(function(e){
        console.log("in promise1 ---- catch");
        console.log(e);
      })
      .finally(function(value){
        console.log('in promise1 ---- finally');
        console.log(value);
      });

      defer1.resolve("hello");
      // defer1.reject("sorry,reject");
     }]);
  </script>
</body>
</html>

其中defer()用于创建一个deferred对象,defer.promise用于返回一个promise对象,来定义then方法。then中有三个参数,分别是成功回调、失败回调、状态变更回调。

其中resolve中传入的变量或者函数返回结果,会当作第一个then方法的参数。then方法会返回一个promise对象,因此可以写成

xxxx
.then(a,b,c)
.then(a,b,c)
.then(a,b,c)
.catch()
.finally()

继续说说上面那段代码,then...catch...finally可以想想成java里面的try...catch...finally。

all()方法

这个all()方法,可以把多个primise的数组合并成一个。当所有的promise执行成功后,会执行后面的回调。回调中的参数,是每个promise执行的结果。

当批量的执行某些方法时,就可以使用这个方法。

   var funca = function(){
        console.log("funca");
        return "hello,funa";
      }
      var funcb = function(){
        console.log("funcb");
        return "hello,funb";
      }
      $q.all([funca(),funcb()])
      .then(function(result){
        console.log(result);
      });

执行的结果:

funca
funcb
array [ "hello,funa", "hello,funb" ]

when()方法

when方法中可以传入一个参数,这个参数可能是一个值,可能是一个符合promise标准的外部对象。     

   var funca = function(){
        console.log("funca");
        return "hello,funa";
      }
      $q.when(funca())
      .then(function(result){
        console.log(result);
      });

当传入的参数不确定时,可以使用这个方法。

hello,funa

以上就是对angularjs 中的promise --- $q服务的资料详细介绍,后续继续补充相关资料,谢谢大家对本站的支持!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网