Tutorial :Is there any way of forcing a set of jquery ajax calls into a queue?


I have an array of data (arrData) which I loop around (10 elements), calling an ajax request on each. As it stands at the moment each ajax call is made in parallel. This means the server receives 10 calls all at once and sends back the data in whatever order it calculates each in. To relieve the server slightly I want to now queue my calls. Therefore, when one set of data is received by ajax it calls the next lookup. Is there any way method of doing this built in to jquery or should I hack my loop and add a recursive callback to each?

$.each(arrData, function(k,v) {      $.getJSON(lookupPath,          { key:k, val:v },          function(data) {              console.log(data); //loopback here?          }      );  });  

UPDATE: I went with the following (as suggested by Scott M.) to get this done:

function doLookup() {      if(k < arrData.length) {          var v = arrData[k];          $.getJSON(lookupPath,              { key:k, val:v },              function(data) {                  console.log(data);                  k++;                  doLookup();              }          );      }  }    var k = 0;  doLookup();  


perhaps you could refactor your server-side code so that it can accept one request and provide one response with all the data you need. This would let you process your data sequentially and within only one thread.


In response to the comment below:

if you absolutely need the calls to be sequential, then you will need to recursively call the getJSON() method. This will guarantee your AJAX requests are separate and in order.


I don't think there is any way to do this in jQuery out of the box. It looks like you're going to have to create a callback function on the Ajax call's success and run it for each element of your array.


ajax in jQuery has an option to enable synchronous mode or not.

$.ajax({async: false});  


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »