場景:
前端JS 異步,嵌套層次太多,維護時 無比痛苦(去年做的一個系統項目,現在回想起來,那時候夠耐心的,那麼多嵌套,搞的邏輯複雜多端)
諸如以下現象:
function(arg1,arg2,function(){
function(arg1,arg2,function(){
function(arg1,arg2,function(){
......
})
})
})
Promise是一個接口,它用來處理的對象具有這樣的特點:在未來某一時刻(主要是異步調用)會從服務端返回或者被填充屬性。其核心是,promise是一個帶有then()函數的對象。
q服務是AngularJS中自己封裝實現的一種Promise實現,相對與Kris Kwal's Q要輕量級的多。
先介紹一下$q常用的幾個方法:
- defer() 創建一個deferred對象,這個對象可以執行幾個常用的方法,比如resolve,reject,notify等
- all() 傳入Promise的數組,批量執行,返回一個promise對象
- when() 傳入一個不確定的參數,如果符合Promise標準,就返回一個promise對象
語法:
var deferred = $q.defer();
var promise = deferred.promise;
// assign behavior before resolving
promise.then(function (data) {
console.log('before:', data);
});
deferred.resolve('done ');
多個 function 異步執行:
defer
.then(a,b)
.then(a,b)
.then(a,b)
.catch()
.finally()
可以把多個primise的數組合併成一個。當所有的promise執行成功後,會執行後面的回調。回調中的參數,是每個promise執行的結果。
當批量的執行某些方法時,就可以使用這個方法
function PromiseCtrl($scope, $q, $timeout) {
// Our promise function with its delay as argument
var getPromise = function(delay) {
// Creates a Deferred object
var deferred = $q.defer();
$timeout(function() {
// Resolve the promise at the end of the delay if said delay was > 0
if(delay > 0) {
deferred.resolve("Success");
} else {
deferred.reject("Fail");
}
}, delay);
// The promise of the deferred task
return deferred.promise;
};
// Init
$scope.result = "Waiting";
/*
* Combines multiple promises into a single promise
* that will be resolved when all of the input promises are resolved
*/
$q.all([
getPromise(1000),
getPromise(2000),
getPromise(3000) // <--- Try something less than 0
]).then(function(value) {
// Success callback where value is an array containing the success values
$scope.result = value;
}, function(reason) {
// Error callback where reason is the value of the first rejected promise
$scope.result = reason;
});
}