加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 18:08:07 所属栏目:安全 来源:网络整理
导读:我有一个递归函数检查每半秒左右的一些数据.该函数返回一个promise.一旦找到数据,我想解决承诺并将数据作为分辨率传递.问题是,承诺不会在函数外部调用.then().这是小提琴: http://jsfiddle.net/btyg1u0g/1/. 这是小提琴代码: 服务: myApp.factory('myServ
我有一个递归函数检查每半秒左右的一些数据.该函数返回一个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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读