我有一个递归函数检查每半秒左右的一些数据.该函数返回一个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()
}
}
});
Run Code Online (Sandbox Code Playgroud)
控制器:
myApp.controller('MyCtrl', function ($scope, myService) {
$scope.name = 'Superhero';
// then is never called
myService.runCheck()
.then(function (message) {
console.log("Resolved outside checkForContent");
});
});
Run Code Online (Sandbox Code Playgroud)
看看这个小提琴。
外部$timeout函数已命名,因此可以从其内部调用它。
$timeout(function inner() {
// ...
Run Code Online (Sandbox Code Playgroud)
然后像这样递归调用:
$timeout(function () {
inner();
}, 400);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1015 次 |
| 最近记录: |