我有这个plunker来说明我的问题:
http://plnkr.co/edit/tsBy2K0xv6bboBlZRM8c
$scope.start = function() {
runThisUntil("Ok");
//here I would like to do this:
//runThisUntil("Ok").then(function () {
//doSomeStuff()
//});
}
$scope.clear = function() {
$scope.responses = [];
}
function runThisUntil(criteria) {
runThis(criteria);
}
function runThis(criteria) {
run().then(function (response) {
if (response == criteria) {
$scope.responses.push("Done");
} else {
$scope.responses.push("Wait");
runThisUntil(criteria);
}
});
}
var okWhen = 10;
var start = 0;
function run() {
var deferred = $q.defer();
$timeout(function () {
if (start !== okWhen) {
start += 1;
deferred.resolve("Bad");
} else {
deferred.resolve("Ok")
start = 0;
}
}, 100);
return deferred.promise;
}
}
我在这里试图模拟的是一种循环形式,我向一个批量工作的http服务器发出请求,并用"还有更多的工作"响应,直到"工作完成"。
当我试图用promise来做这件事时,我最终用$q创建了新的延迟promise,所以我等待解决的最初promise从未得到解决,因为请求被重复了,如果没有完成,我会再次执行相同的函数。
--编辑我想我可以用$scope来做这件事$broadcast(),但如果可能的话,我想通过使用$q来解决这个问题,如果可能的时候不监听事件。
更新:
var app = angular.module('myApp', []);
angular.module('myApp').controller('TestCtrl', ["$timeout", "$interval", "$scope", "$q", function TestCtrl($timeout, $interval, $scope, $q) {
activate();
$scope.responses = [];
function activate() {
$scope.start = function() {
runThisUntil("Ok").then(function() {
$scope.responses.push("Pushed final");;
});
}
$scope.clear = function() {
$scope.responses = [];
}
function runThisUntil(criteria) {
return runThis(criteria);
}
function runThis(criteria) {
return run().then(function (response) {
$scope.responses.push("Done");
}, function () {
$scope.responses.push("Wait");
return runThis(criteria);
});
}
var okWhen = 10;
var start = 0;
function run() {
var deferred = $q.defer();
$timeout(function () {
if (start !== okWhen) {
start += 1;
deferred.reject("Bad");
} else {
deferred.resolve("Ok")
start = 0;
}
}, 100);
return deferred.promise;
}
}
}]);
http://plnkr.co/edit/MYn6otWMmxHFDd41jBpI?p=preview