递归异步函数
Recursive Async function
我有一个关于我遇到的问题的问题。我使用AngularJS作为我的框架,无法访问jQuery或Lodash。
问题所在
我有一个名为"刷新"的功能。该函数通过角度$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);
});
}
我试过什么
我试图在单独的函数中设置请求,并像使用普通的 a-sync 函数一样调用它。
我还尝试了一段时间循环并在完成收集后设置布尔值。唯一的问题是 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)
但您问题中的代码似乎表明总会至少有一行,因此请适当调整。
我将创建一个递归函数来获取数据:
$scope.refresh = function () {
$scope.allDatas = [];
var getData = function(date){
$http({
method: 'GET',
url: 'http://path.to.my.server'+/ date , // should format date her
timeout: 6000
}).then(function (success) {
date = success.date[0].date; //0 is always the newest message
//Do some stuff with the data; all the datas will be available in $scope.allDatas
$scope.allDatas = $scope.allDatas.concat(success.data);
// call again ?
if( /* decide when you stop getting data */ ){
getData(date);
}
}, function (error) {
console.error("Could not retrieve new messages: 'n", error.data);
errcallback(error);
});
}
var date = new Date();
// launch the function
getData(date);
}
相关文章:
- 如何在异步函数中使用javascript对象
- 调用后不异步Ajax忽略函数
- javascript函数中的异步与同步.(Node.js)
- Meteor:异步函数回调异常:onAfterAction
- 从框架中的函数异步加载 Javascript
- 为什么在定义回调/侦听器函数(异步消息传递,port.on)后没有立即设置全局变量
- 将javascript变量传输到插件函数(异步URL)
- 如何从 JavaScript 调用 JQuery 函数(异步调用后)
- 与其他变换函数异步制作不透明度动画
- 两个异步模块函数异步工作
- durandal激活函数异步代码
- 无法使我的示例函数异步
- 当内部函数异步执行某些操作时,如何从外部函数的回调返回值
- Javascript -使函数异步
- 如何使这个同步递归函数异步
- Promise.then()但函数异步运行
- 使用setimeout使命名函数异步化
- Javascript esriRequest (dojo)在函数异步问题
- 返回嵌套函数(异步)
- 我如何使这个JS函数异步