本文介绍了AngularJS,答应与递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用AngularJS答应/然后用递归函数。但当时的功能不叫(没有无错的,成功 - 通知 - 回调被调用)。
I'm trying to use the AngularJS promise/then with a recursive function. But the then-function is not called (none of the error-, success-, notify-callbacks gets called).
下面是我的code:
递归函数
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;
});
我想,当时至少拿到第一通知回调。但没有回调。
然后与递归函数的工作?
I think, the then has to get the first notify-callback at least. But there is no callback.Is then not working with recursive function?
推荐答案
编辑 - 二○一五年十一月一十一日有一个更清洁的方式,如果你不关心通知:
EDIT - 11/11/2015 There is a much cleaner way if you don't care about notify:
loadSection2 = function (){
var apiURL = "http://..."
return $http.get(apiURL)
.then(function(response){
loadCount++;
if (loadCount < 10) {
newSectionArray.push(response.data);
return loadSection2();
}
loadCount = 0;
});
};
旧的答案可以在这里找到:
您可以通过连续传递承诺的所有道路。
You could continuously pass the promise all the way through.
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;
};
这篇关于AngularJS,答应与递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!