AngularJS,承诺具有递归功能

Fau*_*phi 13 javascript recursion promise angularjs

我正在尝试使用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;
};
Run Code Online (Sandbox Code Playgroud)

然后

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;
});
Run Code Online (Sandbox Code Playgroud)

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

Mat*_*erg 23

编辑 - 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;
        });

};
Run Code Online (Sandbox Code Playgroud)

这里有旧答案:

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

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;
};
Run Code Online (Sandbox Code Playgroud)

  • Mathew,我觉得你忘了在你的递归调用中实际传递`deferred`,但这是正确的答案.你遇到的问题是你每次调用方法时都会创建一个新的`deferred`对象,而不是在整个过程中使用相同的对象.所以第一次调用loadSection2时,你会得到deferred1,但是得到解决的延迟实际上是deferred10.传递延迟将有所帮助,或者您可以在方法之外创建变量并使用闭包来访问它. (2认同)