2
不確定q.all第二次未正常工作的原因,例如第二次它不等待所有的承諾得到解決。
請看一下這個例子,然後按「通話服務」按鈕。第一次它等待,直到兩個承諾都解決了,但如果你再次按下按鈕,它立即響應,不知道爲什麼?
http://plnkr.co/edit/JNJmX1fjsmxrxYuiNHJb?p=preview
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $q, MyService1, MyService2) {
$scope.name = 'World';
$scope.Status1 = 'Waiting';
$scope.Status2 = 'Waiting';
$scope.buttonValue = "Call Services";
$scope.doServices = function() {
$scope.Status1 = 'Waiting';
$scope.Status2 = 'Waiting';
$scope.buttonValue = "Working ...";
console.log($scope.Status1)
var promise1 = MyService1.doIt();
var promise2 = MyService2.doIt();
$q.all([promise1, promise2]).then(
function() {
$scope.Status1 = 'Done';
},
function() {
$scope.Status1 = 'Failed';
}
).finally(function() {
$scope.Status2 = 'Done waiting';
$scope.buttonValue = "Call Services";
//promises = null;
});
}
$scope.callServices = function() {
$scope.Status1 = 'Waiting';
$scope.Status2 = 'Waiting';
$scope.doServices();
}
$scope.reset = function() {
$scope.Status1 = 'Waiting';
$scope.Status2 = 'Waiting';
}
});
app.service("MyService1", function($q, $timeout) {
var deferred = $q.defer();
this.doIt = function() {
$timeout(function() {
console.log("Service 1 called!");
deferred.resolve("Service 1 done!");
}, 2000);
return deferred.promise;
}
});
app.service("MyService2", function($q, $timeout) {
var deferred = $q.defer();
this.doIt = function() {
$timeout(function() {
console.log("Service 2 called!");
deferred.resolve("Service 2 done!");
}, 5000)
return deferred.promise;
}
});
感謝您的快速響應。我只是在玩q.all。事實上,我有一個複雜的問題。我有多個服務調用進行服務器端數據庫調用,我想至少等待其中的幾個完成處理其餘代碼。這就是爲什麼我使用服務進行模擬的原因,但我認爲q和timeout的雙重用法都會導致問題的答案。你的建議解決了這個問題。 – user1829319