AngularJS 中的Promise --- $q服务详解
先说说什么是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服务详解的更多相关文章
- Angularjs中的promise
promise 是一种用异步方式处理值的方法,promise是对象,代表了一个函数最终可能的返回值或抛出的异常.在与远程对象打交道非常有用,可以把它们看成一个远程对象的代理. 要在Angular中创建 ...
- angular $q promise详解
前言 通过本文,你大概能清楚angular promise是个啥,$q又是个啥,以及怎么用它.这里咱们先灌输下promise的思想. 下面写的全是废话,一些看着高逼格其实没什么大作用的概念,想知道$q ...
- winxp计算机管理中服务详解
winxp计算机管理中服务详解01 http://blog.sina.com.cn/s/blog_60f923b50100efy9.html http://blog.sina.com.cn/s/blo ...
- Android中Service(服务)详解
http://blog.csdn.net/ryantang03/article/details/7770939 Android中Service(服务)详解 标签: serviceandroidappl ...
- WCF中队列服务详解
WCF中队列服务详解 一.引言 在前面的WCF服务中,它都要求服务与客户端两端都必须启动并且运行,从而实现彼此间的交互.然而,还有相当多的情况希望一个面向服务的应用中拥有离线交互的能力.WCF通过服务 ...
- 【转】SSH服务详解
[转]SSH服务详解 第1章 SSH服务 1.1 SSH服务协议说明 SSH 是 Secure Shell Protocol 的简写,由 IETF 网络工作小组(Network Working Gro ...
- (转)SSH服务详解
SSH服务详解 原文:http://www.cnblogs.com/clsn/p/7711494.html 第1章 SSH服务1.1 SSH服务协议说明SSH 是 Secure Shell Proto ...
- python中argparse模块用法实例详解
python中argparse模块用法实例详解 这篇文章主要介绍了python中argparse模块用法,以实例形式较为详细的分析了argparse模块解析命令行参数的使用技巧,需要的朋友可以参考下 ...
- python中requests库使用方法详解
目录 python中requests库使用方法详解 官方文档 什么是Requests 安装Requests库 基本的GET请求 带参数的GET请求 解析json 添加headers 基本POST请求 ...
随机推荐
- Duilib源码分析(五)UI布局—Layout与各子控件
接下来,继续分析duilib之UI布局Layout,目前提供的布局有:VerticalLayout.HorizontalLayout.TileLayout.TabLayout.ChildLayout分 ...
- 安装spark ha集群
安装spark ha集群 1.默认安装好hadoop+zookeeper 2.安装scala 1.解压安装包 tar zxvf scala-2.11.7.tgz 2.配置环境变量 vim /etc/p ...
- Windows安装程序 报错 “已安装了较新版本” 导致无法安装程序的解决方法
打开注册表 HKEY_CURRENT_USER\Software\Microsoft\Installer\Products ,“查找”程序名称 如果有程序名和安装程序相同的 ,删除整个 项 ! 然后就 ...
- java中注解的使用与实例 (二)
java 注解,从名字上看是注释,解释.但功能却不仅仅是注释那么简单.注解(Annotation) 为我们在代码中添加信息提供了一种形式化的方法,是我们可以在稍后 某个时刻方便地使用这些数据(通过 解 ...
- Spark 资源池简介
在一个application内部,不同线程提交的Job默认按照FIFO顺序来执行,假设线程1先提交了一个job1,线程2后提交了一个job2,那么默认情况下,job2必须等待job1执行完毕后才能执行 ...
- 如何在windows上编译Chromium (CEF3) 并加入MP3支持(二)
时隔一年,再次编译cef3,独一无二的目的仍为加入mp3支持.新版本的编译环境和注意事项都已经发生了变化,于是再记录一下. 一.编译版本 cef版本号格式为X.YYYY.A.gHHHHHHH X为主版 ...
- Day 2:增加SplashScreen
If you want to add just single image, then create a pic in the size of 480*800 and name it as Splash ...
- Agile
I think Agile development methodologies is something we get from our practice. It can be just acknow ...
- Data对象
var myDate = new Date(); Date()返回当日的日期 例如今天是2016/8/19 getFullYear()返回当前日期的年 myDate.getFullYear() 201 ...
- C#详解format函数,各种格式化
一.String Format for Double Digits after decimal point This example formats double to string with fix ...