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