var ngApp=angular.module('ngApp',[]);

/*******************************************************************
* $q为内置服务
****************************************************************/
ngApp.factory('UserInfoService',['$http','$q',function($http,$q){
return{
query:function(){
var defer=$q.defer(); //声明延后执行
$http({method:'GET',url:'data/students.json'}).
success(function(data,status,headers,config){
defer.resolve(data); //声明执行成功
console.log('UserInfoService success');
}).
error(function(data,status,headers,config){
defer.reject(); //声明执行失败
}); return defer.promise; //返回承诺,返回获取数据的API
}
}
}]); ngApp.controller('MainCtrl',['$scope','UserInfoService',function($scope,UserInfoService){
     var promise = UserInfoService.query(); //同步调用,获取承诺接口
promise.then(function(data){
$scope.user=data; //调用承诺接口resolove()
console.log('MainCtrl ...');
},function(data){
$scope.user={error:'数据不存在。。。'}; //调用承诺接口reject();
}); }]);

  

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

最新文章

  1. How to change hostname on SLE
  2. 关于启动 SecureCRT 遇到一个致命的错误且必须关闭
  3. 连载《一个程序猿的生命周期》-6、自学C++,二级考过后,为工作的机会打下了基础
  4. ASP.NET Web Api 安全性(转载)
  5. linux(debian)下邮件发送
  6. ofbiz进击 。 ofbiz 退货流程(包含获取可退货项流程分析 以及 取消退货项的过程分析)
  7. UnicodeDecodeError: &#39;ascii&#39; codec can&#39;t decode byte 0xe9 in position 0: ordinal not in range(128) 解决办法
  8. [Java] Steam文件输入流
  9. HDU-1300(基础方程DP-遍历之前所有状态)
  10. 终于懂了:Delphi的函数名不是地址,取地址必须遵守Object Pascal的语法(Delphi和C的类比:指针、字符串、函数指针、内存分配等)good
  11. openssl 加密
  12. 转-Web Service中三种发送接受协议SOAP、http get、http post
  13. RubyGem默认源安装太慢,修改国内淘宝源
  14. 第二节. SignalR开篇以及如何指定传输协议
  15. 自动化工具-ansible服务部署与使用
  16. Lambda表达式Contains方法(等价于SQL语句中的like)使用注意事项
  17. AI 主成分分析(PCA)
  18. 如何遍历Set对象
  19. 3.The significance of Books 书本的意义
  20. python 使用for循环简单爬取图片(1)

热门文章

  1. python获取函数名
  2. Word中公式从单栏排版变为双栏排版后公式和编号错开了
  3. Linux(CentOS)下的vsftpd服务器配置-五岳之巅
  4. 二十四种设计模式:观察者模式(Observer Pattern)
  5. js清空子元素,创建新的子元素
  6. PowerShell中的一个switch的例子
  7. Linux内核源码情景分析-系统调用
  8. :视频播放器与Handler 完美调用
  9. Microsoft.Office.Workflow.Actions Namespace
  10. TestNG参数化测试Spring应用Dubbo接口