<!-- lang: js -->
var deferred = $q.defer();
var promise = deferred.promise;
promise.then(function success(data) {//成功
console.log(data);
},
function error(error) {//錯(cuò)誤
console.error(error);
},
function notification(notification) {//狀態(tài)
console.info(notification);
}));
var progress = 0;
var interval = $interval(function() {
if (progress >= 100) {
$interval.cancel(interval);
deferred.resolve('All done!');//成功消息
}
progress += 10;
deferred.notify(progress + '%...'); //狀態(tài)消息
}, 100)
不用 then() 的第二個(gè)參數(shù)审胸,還有另外一種選擇卓缰,你可以用鏈?zhǔn)降?catch()蛛株,在 promise 鏈中發(fā)生異常的時(shí)候它會(huì)被調(diào)用(可能在很多鏈之后)抓半。
<script type="text/javascript">
var myAppModule = angular.module("myApp",[]);
myAppModule.controller("myctrl",["$scope","$q",function($scope, $ q ){
$scope.test = 1;//這個(gè)只是用來測(cè)試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>
鏈?zhǔn)教幚?/p>
var deferred = $q.defer();
var promise = deferred.promise;
promise
.then(function(val) {
console.log(val);
return 'B';
})
.then(function(val) {
console.log(val);
return 'C'
})
.then(function(val) {
console.log(val);
});
deferred.resolve('A');
這會(huì)在控制臺(tái)輸出以下結(jié)果:
<!-- lang: js -->
A
B
C
reject,會(huì)調(diào)用catch,不調(diào)用then囊嘉,在鏈?zhǔn)秸{(diào)用的時(shí)候使用
$q.reject("instant reject") .catch(function (err) { console.log(err); });
我還提到了** $q.all(),允許你等待并行的 promise 處理革为,當(dāng)所有的 promise 都被處理結(jié)束之后扭粱,調(diào)用共同的回調(diào)。在 Angular 中震檩,這個(gè)方法有兩種調(diào)用方式: 以 Array 方式或 Object **方式琢蛤。Array 方式接收多個(gè) promise ,然后在調(diào)用 .then() 的時(shí)候使用一個(gè)數(shù)據(jù)結(jié)果對(duì)象抛虏,在結(jié)果對(duì)象里面包含了所有的 promise 結(jié)果博其,按照輸入數(shù)組的順序排列:
<!-- lang: js -->
$q.all([promiseOne, promiseTwo, promiseThree])
.then(function(results) {
console.log(results[0], results[1], results[2]);
});
第二種方式是接收一個(gè) promise 集合對(duì)象,允許你給每個(gè) promise 一個(gè)別名迂猴,在回調(diào)函數(shù)中可以使用它們(有更好的可讀性):
<!-- lang: js -->
$q.all({ first: promiseOne, second: promiseTwo, third: promiseThree })
.then(function(results) {
console.log(results.first, results.second, results.third);
});
我建議使用數(shù)組表示法慕淡,如果你只是希望可以批處理結(jié)果,就是說沸毁,如果你把所有的結(jié)果都平等處理峰髓。而以對(duì)象方式來處理,則更適合需要自注釋代碼的時(shí)候以清。
另一個(gè)有用的方法是** $q.when()**儿普,如果你想通過一個(gè)普通變量創(chuàng)建一個(gè) promise ,或者你不清楚你要處理的對(duì)象是不是 promise 時(shí)非常有用掷倔。
<!-- lang: js -->
$q.when('foo')
.then(function(bar) {
console.log(bar);
});
$q.when(aPromise)
.then(function(baz) {
console.log(baz);
});
$q.when(valueOrPromise)
.then(function(boz) {
// well you get the idea.
})
$q.when() 在諸如服務(wù)中的緩存這種情況也很好用:
接收第一個(gè)參數(shù)為一個(gè)任意值或者是一個(gè)promise對(duì)象眉孩,其他3個(gè)同promise的then方法,返回值為一個(gè)promise對(duì)象。第一個(gè)參數(shù)若不是promise對(duì)象則直接運(yùn)行success回調(diào)且消息為這個(gè)對(duì)象,若為promise那么返回的promise其實(shí)就是對(duì)這個(gè)promise類型的參數(shù)的一個(gè)包裝而已浪汪,被傳入的這個(gè)promise對(duì)應(yīng)的defer發(fā)送的消息巴柿,會(huì)被我們when函數(shù)返回的promise對(duì)象所接收到。
var defer1 = $q.defer();
var promise1 = defer1.promise;
var promise2 = $q.when(promise1, function(num) {
console.log("s" + num);
}, function() {
console.log("e");
});
defer1.reject(1);
運(yùn)行結(jié)果:
e
<!-- lang: js -->
angular.module('myApp').service('MyService', function($q, MyResource) {
var cachedSomething;
this.getSomething = function() {
if (cachedSomething) {
return $q.when(cachedSomething);
}
// on first call, return the result of MyResource.get()
// note that 'then()' is chainable / returns a promise,
// so we can return that instead of a separate promise object
return MyResource.get().$promise
.then(function(something) {
cachedSomething = something
});
};
});
然后可以這樣調(diào)用它:
<!-- lang: js -->
MyService.getSomething()
.then(function(something) {
console.log(something);
});