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

时间:2022-04-22
本文章向大家介绍AngularJS 中的Promise --- $q服务详解,主要内容包括什么是Promise、$q服务、all()方法、when()方法、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

先说说什么是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