我有一个递归函数,每半秒左右检查一些数据。该函数返回一个promise。一旦找到数据,我想解决承诺并将数据作为分辨率传递。问题是,承诺不会在函数外部调用.then()。这是小提琴:http://jsfiddle.net/btyg1u0g/1/。
这是小提琴代码:
服务:
myApp.factory('myService', function($q, $timeout) {
var checkStartTime = false;
var checkTimeout = 30000;
function checkForContent() {
var deferred = $q.defer();
// simulating an $http request here
$timeout(function () {
console.log("Checking...");
if (!checkStartTime) checkStartTime = new Date();
// this would normally be 'if (data)'
if ((new Date()) - checkStartTime > 3000) {
deferred.resolve("Finished check");
checkStartTime = false; // reset the timeout start time
} else {
// if we didn't find data, wait a bit and check again
$timeout(function () {
checkForContent();
}, 400);
}
}, 5);
// then is called in here when we find data
deferred.promise.then(function(message) {
console.log("Resolved inside checkForContent");
});
return deferred.promise;
}
return {
runCheck: function() {
return checkForContent()
}
}
});
控制器:
myApp.controller('MyCtrl', function ($scope, myService) {
$scope.name = 'Superhero';
// then is never called
myService.runCheck()
.then(function (message) {
console.log("Resolved outside checkForContent");
});
});
答案 0 :(得分:1)
查看this fiddle。
外部$timeout
函数已命名,因此可以从内部调用它。
$timeout(function inner() {
// ...
然后像这样递归地调用它:
$timeout(function () {
inner();
}, 400);