AngularJS,承诺具有递归功能

 李伟祥祥 发布于 2023-02-10 11:15

我正在尝试使用AngularJS承诺/然后使用递归函数.但是没有调用then-function(没有调用error-,success-,notify-callbacks).

这是我的代码:

递归函数

loadSection2 = function() {

    var apiURL = "http://..."

    var deferred = $q.defer();

    $http({
        method: "GET",
        url: apiURL
    }).success(function(result, status, headers, config) {
        console.log(result);
        loadCount++;
        if(loadCount < 10) {
            newSectionArray.push(result);
            loadSection2(); 
        } else {
            loadCount = 0;
            deferred.resolve();
            return deferred.promise;
        }
    }).error(function() {
        return deferred.reject();
    });
    deferred.notify();
    return deferred.promise;
};

然后

loadSection2().then(function() {
    console.log("NEW SECTIONS LOADED, start adding to document");
    addContent();
}, function() {
    console.log("ERROR CALLBACK");
}, function() {
    console.log("NOTIFY CALLBACK");
}).then(function() {
    loadScrollActive = false;
});

我认为,至少必须得到第一个通知回调.但是没有回调.那么不使用递归函数?

1 个回答
  • 编辑 - 11/11/2015如果您不关心通知,有一个更清洁的方式:

    loadSection2 = function (){
        var apiURL = "http://..."
        return $http.get(apiURL)
            .then(function(response){
                loadCount++;        
                if (loadCount < 10) {
                    newSectionArray.push(response.data);
                    return loadSection2();
                }
                loadCount = 0;
            });
    
    };
    

    这里有旧答案:

    你可以不断地将承诺传递给我.

    loadSection2 = function(deferred) {
    
        if(!deferred){
            deferred = $q.defer();
        }
        var apiURL = "http://..."
    
        $http({
            method: "GET",
            url: apiURL
        }).success(function(result, status, headers, config) {
            console.log(result);
            loadCount++;
            if(loadCount < 10) {
                newSectionArray.push(result);
                loadSection2(deferred); 
            } else {
                loadCount = 0;
                deferred.resolve();
                return deferred.promise;
            }
        }).error(function() {
            return deferred.reject();
        });
        deferred.notify();
        return deferred.promise;
    };
    

    2023-02-10 11:18 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有