簡體   English   中英

jQuery for ajax調用循環,等待一切完成

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

他有一個問題,我需要將多個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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM