简体   繁体   中英

jquery parallel ajax calls loop one after another

When i execute below script it creating all 1000 ajax requests and when the transaction gets to about ~3k it never did finish. so i am trying to make slab based parallel ajax requests,

How do i create parallel ajax requests one after another? I want to create first 100 parallal ajax requests after completing the 1st 100 ajax responses then create 2nd position 200 parallel ajax requests.

Here is my array

var tasks=[{100 urls},{200 urls},{400 urls},{600 urls},{800 urls},{1000 urls}];
$.each(tasks,function(index,item){
  $.each(item.urls,function(key,val){
    $.aja(val.url,function(response){
    // .... do some work
    });
  });
});

Every ajax call runs asynchronously. So you may wait each task's async ajax calls done and run next task and so on.

Below script uses Promise pattern( jquery.when ) to wait done each task's async ajax calls.

var tasks=[{100 urls},{200 urls},{400 urls},{600 urls},{800 urls},{1000 urls}];

function runTasks(index) {
  var item = tasks[index];
  return $.when($.map(item.urls, function(key, val) {
    return $.ajax(val.url);
  })).then(function() {
    if (tasks[index + 1]) {
      return runTask(index + 1);
    } else {
      return true;
    }
  });
}

runTasks(0).then(function() {
  // execute when all tasks done
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM