我有这个说明我的问题:
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服务器发出请求,该服务器分批工作并响应"还有更多工作"直到"工作完成"。
当我尝试使用promises执行此操作时,我最终使用$ q创建了新的延期承诺,因此我等待解决的初始承诺永远不会得到解决,因为请求被重复,我通过执行相同的函数来执行如果没有完成,请再次参加。
- 编辑 我想我可以用$ scope。$ broadcast()完成它,但我想尽可能使用$ q来解决这个问题,如果可能的话不要听事件。
答案 0 :(得分:0)
更新:
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;
}
}
}]);