angular $q服务的用法

Promise是一种和callback有相似功能却更强大的异步处理模式,有多种实现模式方式,好比著名的Q还有JQuery的Deffered。javascript

什么是Promise

之前了解过Ajax的都能体会到回调的痛苦,同步的代码很容易调试,可是异步回调的代码,会让开发者陷入泥潭,没法跟踪,好比:html

funA(arg1,arg2,function(){
    funcB(arg1,arg2,function(){
        funcC(arg1,arg2,function(){
             xxxx....
        })
    })   
})

 

自己嵌套就已经很不容易理解了,加上不知什么时候才触发回调,这就至关于雪上加霜了。java

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

deferABC.resolve(xxx)
.then(funcSuccess(){},funcError(){},funcNotify(){});

 

当resolve内的对象成功执行,就会触发funcSuccess,若是失败就会触发funcError。有点相似数组

deferABC.resolve(function(){
    Sunccess:funcSuccess,
    error:funcError,
    notify:funcNotify
})

 

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

好比,小白在上学时很懒,平时总让舍友带饭,而且事先跟他说好了,若是有韭菜鸡蛋就买这个菜,不然就买西红柿炒鸡蛋;不管买到买不到都要记得带包烟。markdown

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

 

 
  

$q服务

q服务是AngularJS中本身封装实现的一种Promise实现,相对与Kris Kwal's Q要轻量级的多。
先介绍一下$q经常使用的几个方法:app

  • 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);
            });

 

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

相关文章
相关标签/搜索