Lee
Lee

Reputation: 1495

Javascript - Pause loop until AJAX completes

I have a loop that fires off AJAX requests, is it possible to pause the loop until the AJAX has returned for each iteration?

 for (var i = 0; i < 5; i++) {

     var data = "i=" + 1;
     var ajax = $.ajax({
         url: '/ajax.php',
         type: 'post',
         data: data,
         success: function(result)
         {
           //alert(result);
         }                                                      
     });

     //pause the for loop here

     ajax1.done(function (result) {
         //continue the for loop
     }); 
 }

Upvotes: 0

Views: 89

Answers (2)

Aurel B&#237;l&#253;
Aurel B&#237;l&#253;

Reputation: 7963

In ES6 you can probably use the async / await syntax:

for (let i = 0; i < 5; i++) {
  let data = "i=" + i;
  let result = await $.ajax({
    url: '/ajax.php',
    type: 'post',
    data: data
  });
  console.log(result);
}

(This needs to be done in a async function though.)

Other than that there is no syntax in JS that would allow this, so you have to adapt your code:

function requestRange(start, end) {
  function request(i) {
    if (i >= end) return;
    let data = "i=" + i;
    let ajax = $.ajax({
      url: '/ajax.php',
      type: 'post',
      data: data
    });
    ajax.done(function (result) {
      console.log(result);
      request(i + 1);
    }); 
  }
  request(start);
}

requestRange(0, 5);

Upvotes: 0

Tirth Shah
Tirth Shah

Reputation: 624

You want the Ajax calls to be asynchronous but also execute successively. Instead of a for loop, you can use recursion.

doAjax (index, maxNumber) {

     var data = "i=" + index;
     var ajax = $.ajax({
         url: '/ajax.php',
         type: 'post',
         data: data,
         success: function(result)
         {
           //alert(result);
         }                                                      
     });
     ajax1.done(function (result) {
         if(index<=maxNumber){
               doAjax(index + 1, maxNumber);
     });
}

You can call this as doAjax(1, 5) which will make all ajax calls from 1 to 5 after the previous one is over.

Upvotes: 1

Related Questions