他我有问题
我需要将多个AJAX调用发送到同一URL,但使用不同的数据。
我需要分块发送它,并等待所有请求完成,然后再执行_.each函数。

我做了一个简单的块函数,将我的数组切成薄片并将其分组。

我的代码:

 ---- 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 -----


我需要获得一个完整的数组,其中包含我所有的resp数据

我无法执行$ .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);
});

09-27 00:59
查看更多