jQuery for循环ajax调用和等待,直到所有完成
jQuery for loop on ajax call and wait until all is done
我有个问题我需要发送多个AJAX调用到相同的URL,但不同的数据。我需要把它分成块发送,直到所有的请求都在我的_。每个函数。
我做了一个简单的chunk函数,将我的数组切片并滑动到组中。
我代码: ---- js ----
batch = [0,1,2,3,4,5,....] // big array
var xhr = chunk(batch, 20);
for (i=0; i < xhr.length ; i++ ) {
//loop number of time of xhr.length
ajax.call("/", "POST", {batch: xhr[i]}).done(function(resp){
arrayResp.push(resp);
});
}
/// after all ajax calls and arrayResp is done
exectue
_.each(arrayResp, function (element) {
//do somting
});
----- /js -----
我需要得到一个完整的数组来保存我所有的数据
我不能做$.when(),因为我不能命名函数我不知道如何在这个函数中使用$.Deferred()你能帮我吗?
谢谢!
var res = [];
// this may not be needed
var arrayResp = [];
batch = [0,1,2,3,4,5,....] // big array
var xhr = chunk(batch, 20);
for (i=0; i < xhr.length ; i++ ) {
//loop number of time of xhr.length
// push `ajax` jQuery promise to `res`
res.push(
ajax.call("/", "POST", {batch: xhr[i]})
// this may not be needed,
// see `arguments` at `.then`
.done(function(resp){
arrayResp.push(resp);
})
);
}
// when all `xhr` complete ,
// process array of `xhr` jQuery promises
$.when.apply($, res)
.then(function() {
// do stuff with `arrayResp``
console.log(arrayResp, arguments);
});
相关文章:
- Javascript在for循环中等待处理请求
- JavaScript循环并等待函数
- 在等待异步任务时永久循环
- 等待循环调用的所有承诺完成
- 如何让foreach循环等待$http.get完成后再继续
- 如何使for循环等待回调返回值
- 在 JS 中使 for 循环在没有库的情况下等待
- Nodejs async.each 等待第一个循环
- 如何在数组中循环,等待每个项目之间的时间
- 如何在for循环中等待一个,直到ajax调用完成
- NodeJS - Bluebird:等待循环完成
- 等待循环中的函数完成
- 等待循环完成
- 使异步/等待循环按顺序执行
- 在输出数据之前,等待循环完成每个数组项的 $.getJSON
- Jquery等待循环中带有ajax调用的函数完成-单击按钮后刷新
- 等待循环结束并执行第二个函数
- 如何等待'等待'循环返回
- 如何在退出循环之前等待循环内的异步进程完成
- Javascript:等待循环中的函数在下一次迭代之前完成执行