Angularjs 角度承诺解析函数内部而非外部

Angularjs 角度承诺解析函数内部而非外部,angularjs,promise,Angularjs,Promise,我有一个递归函数,每隔半秒左右检查一次数据。函数返回一个承诺。一旦我找到了数据,我想解析承诺并将数据作为解析传递。问题是,promise不会在函数外部调用.then()。这是小提琴: 这是小提琴的代码: 服务: myApp.factory('myService', function($q, $timeout) { var checkStartTime = false; var checkTimeout = 30000; function checkForContent

我有一个递归函数,每隔半秒左右检查一次数据。函数返回一个承诺。一旦我找到了数据,我想解析承诺并将数据作为解析传递。问题是,promise不会在函数外部调用.then()。这是小提琴:

这是小提琴的代码:

服务:

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

});
退房

outter
$timeout
函数已命名,因此可以从内部调用它

$timeout(function inner() {
  // ...
然后递归调用它,如下所示:

$timeout(function () {
  inner();
}, 400);

它调用了checkForContent中的一个。它不调用控制器中的一个。我应该看到两个日志:“在checkForContent内部解决”和“在checkForContent外部解决”。你做得不对。。你从来没有解决你最初返回的承诺。每次函数创建一个新的承诺,最后一个承诺得到解决,您已经将其链接到函数中。但是函数调用期间返回的承诺从未得到解决。啊,我明白了,我没有意识到我每次都在创建一个新的承诺。我想你有,但让我测试一下。
函数checkForData(){return$q.when().then(函数poll(){return data | |$timeout(400)。then(poll);})
-为您解决了这个问题。没有理由让代码长度超过3行。
$timeout
已经返回一个承诺,承诺链,并且您有一个延迟的反模式。@RobbyAllsopp是这样的吗?所以笨拙:让我们看看上面评论中的代码示例。