jQuery for循环ajax调用和等待,直到所有完成

jQuery for loop on ajax call and wait until all is done

本文关键字:等待 循环 for ajax 调用 jQuery      更新时间:2023-09-26

我有个问题我需要发送多个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);
});