我对遇到的问题有疑问。我使用 AngularJS 作为我的框架,无法访问 jQuery 或 Lodash。
问题
我有一个叫做“刷新”的功能。该函数通过 Angular $http 进行异步调用以从服务器获取新数据。从我指定的日期起,服务器只给我 25 个新的更新。因此,要获取所有新消息,我需要调用服务器(并在每次获取数据时更新“updateDate”)直到它告诉我它没有更多消息(空数组)。
代码示例
$scope.refresh = function () {
var date = new Date();
$http({
method: 'GET',
url: 'http://path.to.my.server',
timeout: 6000
}).then(function (success) {
date = success.date[0].date; //0 is always the newest message
callback(success.data);
//Do some stuff with the data
}, function (error) {
console.error("Could not retrieve new messages: \n", error.data);
errcallback(error);
});
我尝试过的
我试图在一个单独的函数中设置请求,并像使用普通异步函数一样调用它。
我还尝试了 while 循环并在完成收集后设置了一个 bool 值。唯一的问题是 while 循环不会等待调用结束(否则它不会是异步的)并且会产生相当令人印象深刻的循环(还不是无限的,但足以让我的程序崩溃)。
我在考虑 for 循环,但我不知道应该进行多少次迭代。它可以是 1,也可以是 5 或更多。
我知道递归函数是如何工作的,但我不知道我应该如何使用异步递归函数。欢迎任何建议或解决方案。 (如果有人知道其他解决方案,我就不必递归了)
最佳答案
使异步函数递归并没有什么特别特别的,您只是不必担心堆栈用完。
只需将您的 ajax 调用隔离到一个函数中,然后让该函数调用自身,直到它拥有数据的完整图片:
$scope.refresh = function () {
var date = new Date();
var results = [];
gather();
function gather() {
$http({
method: 'GET',
url: 'http://path.to.my.server',
timeout: 6000
// presumably using `date` here?
}).then(function(success) {
// This seems to assume you'll always have at least
// one row, which doesn't seem to match with your description
date = success.data[0].date; //0 is always the newest message
if (thereAreNewResults) {
results.push.apply(results, success.data);
gather();
} else {
// We're done
callback(results);
}
}, function (error) {
console.error("Could not retrieve new messages: \n", error.data);
errcallback(error);
});
}
};
这并不意味着是完整的和完美的,但它应该让您朝着正确的方向前进。
注意我的 if (thereAreNewResults)
。我原以为那会是 if (success.data.length)
但您问题中的代码似乎表明总是至少有一行,因此请适当调整。
关于javascript - 递归异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36771590/