【发布时间】:2015-11-05 09:50:27
【问题描述】:
我有这个 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 来解决这个问题,如果可能的话不要监听事件。
【问题讨论】:
标签: javascript angularjs promise q deferred