JavaScript异步调用循环
我想在循环中检查列表中的3000个项目。在每一步我必须在页面上进行异步httprequest。使之成为一个递归函数IST扔InternalError: too much recursion
这是到目前为止我的代码:JavaScript异步调用循环
var iteratorObject = new function(){
this.currentStep = -1;
this.iterationList = {};
this.start = function(list){
this.iterationList = list;
this.next(0);
}
this.next = function(value) {
this.currentStep = value;
if(this.currentStep +1 == this.iterationList.length){
return
}
var currentID = this.iterationList[this.currentStep];
//Do Aysnc HttpRequest on succeed call this.next(value +1);
}
}
var iterator = iteratorObject;
var iterationList = Object.keys([Object]);
iterator.start(iterationList);
如何更改我的代码以避免递归函数,只有一次处理一个请求?
我想补充另一种解决方案,我认为这是一个有趣的问题,所以这里的东西我熟了基于原来的解决方案:
function Iterator(doWork) {
var done, start;
done = function() {
start();
};
start = function() {
doWork(done);
};
// Export this method.
this.start = start;
}
和使用是:
<ul id="times">
Iterations...
</ul>
<script type="text/javascript">
$(function() {
var maxIterations = 7000,
$times = $('#times');
var iterator = new Iterator(function (next) {
var now = new Date();
window.setTimeout(function() {
var ms = (new Date() - now);
$times.append($('<li></li>').text('Iteration ' + ($times.find('li').length + 1) + ': ' + ms + ' ms'));
maxIterations -= 1;
if (maxIterations > 0) {
next();
}
}, 100);
});
iterator.start();
});
</script>
这导致了一个inter原因观察:Chrome比Internet Explorer有更好的计时器。
Chrome的输出样本:
Iteration 5687: 101 ms
Iteration 5688: 101 ms
Iteration 5689: 101 ms
Iteration 5690: 101 ms
Iteration 5691: 101 ms
Iteration 5692: 101 ms
Iteration 5693: 101 ms
Iteration 5694: 101 ms
Iteration 5695: 100 ms
Iteration 5696: 101 ms
Iteration 5697: 101 ms
Iteration 5698: 101 ms
Iteration 5699: 102 ms
现在的Internet Explorer:
•Iteration 5687: 92 ms
•Iteration 5688: 93 ms
•Iteration 5689: 108 ms
•Iteration 5690: 93 ms
•Iteration 5691: 109 ms
•Iteration 5692: 92 ms
•Iteration 5693: 93 ms
•Iteration 5694: 109 ms
•Iteration 5695: 93 ms
•Iteration 5696: 92 ms
•Iteration 5697: 109 ms
•Iteration 5698: 93 ms
•Iteration 5699: 108 ms
哇,这看起来真的像完美的解决方案我问题。谢谢 – 2015-02-11 01:44:53
@southzrgw嘿没问题。很高兴它很有用。 – Paul 2015-02-11 22:47:15
我遇到这种类型的问题,当我想从外部数据库复制记录到sql lite db使用javascript。 一般for循环不会让你作出这样的等待Ajax请求调用到下一次迭代递归代码,那么我建议你的是:
- 使你的代码为全球尽可能把所有的对象以相同的方式
- 得到的对象将它们放到一个表
- 做一个函数,对象作为参数的每一次表和 它 完成,将与下一个元素再次调用它自己的要求,直到达到表的末尾。
例如:
function recursive_calls(var elements[],var currentPosition){
if(currentPosition<elements.length){
$.ajax({
url:some_api/elements[i].id,
method:'get',
success:function(res){
//after some time ajax success function is fired
//do some stuff here
//call recursive_calls function again
currentPosition++;
recursive_calls(elements,currentPosition);
}
});
}
}
你不能在'for'循环,除非你想要写一个框架,做_promises_做到这一点。你看起来像你很接近 - 只需重写'next',以便查看'currentStep'而不需要'value'。 – 2015-02-09 00:02:00
在回调中调用下一个仍然是递归函数?我有一种方法可以在currentStep上调用next()函数来获取事件列表。 对不起,我有点雏在JS – 2015-02-09 00:06:23
你可以看看这个jsbin我准备:http://jsbin.com/kacabu/1/edit?js,console – 2015-02-09 00:47:17