angularjs – Angular promise在函数内解析但不在外部

前端之家收集整理的这篇文章主要介绍了angularjs – Angular promise在函数内解析但不在外部前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个递归函数检查每半秒左右的一些数据.该函数返回一个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");
    });

});

解决方法

查看 this fiddle.

out $$timeout命名为可以从内部调用.

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

然后像这样递归调用它:

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

猜你在找的Angularjs相关文章