gpt4 book ai didi

angularjs - Angular promise 在函数内部而不是在外部解析

转载 作者:行者123 更新时间:2023-12-04 21:41:22 25 4
gpt4 key购买 nike

我有一个递归函数,每半秒左右检查一些数据。该函数返回一个 promise 。找到数据后,我想解析 promise 并将数据作为解析传递。问题是,promise 不会在函数之外调用 .then() 。这是 fiddle :http://jsfiddle.net/btyg1u0g/1/ .

这是 fiddle 代码:

服务:

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()
}
}
});

Controller :
myApp.controller('MyCtrl', function ($scope, myService) {
$scope.name = 'Superhero';

// then is never called
myService.runCheck()
.then(function (message) {
console.log("Resolved outside checkForContent");
});

});

最佳答案

退房 this fiddle .

$timeout函数被命名,所以它可以从自身内部调用。

$timeout(function inner() {
// ...

然后像这样递归地调用它:
$timeout(function () {
inner();
}, 400);

关于angularjs - Angular promise 在函数内部而不是在外部解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25515232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com