【发布时间】:2014-01-03 15:08:24
【问题描述】:
我正在尝试将 AngularJS 的 promise/then 与递归函数一起使用。但是没有调用 then 函数(没有调用错误、成功、通知回调)。
这是我的代码:
递归函数
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;
});
我认为,那么至少必须获得第一个通知回调。但是没有回调。 那么是不是使用递归函数?
【问题讨论】:
-
你能给我们一个jsfiddle吗?
-
我看到的一件事是你不能从回调函数中返回一些东西。所以在 .success 和 .error 中返回 deferred.promise 实际上什么都不做。虽然不是问题的原因。
-
'loadCount' 定义在哪里?而且,
notify不像你想象的那样工作。我在角度回购中有一个未解决的问题-> github.com/angular/angular.js/issues/5277 -
嗯,有一个解决问题的答案,但现在它消失了。问题是,每次调用 loadSection2() 时都会初始化“延迟”。 @Rifat:通知对我有用。只要 promise 没有解决,notify-callback 就会被调用。
标签: javascript angularjs recursion promise