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)