How to execute sequential asynchronous ajax requests with a given number of threads

I need to do sequential asynchronous ajax requests with limited threads. At the moment, I am only allowed to occupy one thread on the web server, so I can only execute one ajax request.

I have the following function that helps me when I am allowed to use only one thread at a time.

function initiateChain() {
    var i = 0;
    var tasks = arguments;
    var callback = function () {
      i += 1;
      if (i != tasks.length) {
        tasks[i](callback); //block should call callback when done otherwise loop stops
      }
    }
    if (tasks.length != 0) {
      tasks[0](callback); //initiate first one
    }
  }

Tell me if I have three helper functions ajax

 function getGadgets(callback) {
         //ajax call
         callback(); // I call this in complete callback of $.ajax
 }

 function getBooks(callback) {
         //ajax call
         callback(); // I call this in complete callback of $.ajax
 }

 function getDeals(callback) {
         //ajax call
         callback(); // I call this in complete callback of $.ajax
 }

the next call guarantees that no more than 1 ajax request will be made from this client

initiateChain(getGadgets, getBooks, getDeals);

Now I need to strengthen initiateChain to support an arbitrary number of threads. Let's say I am allowed to use 2 or n number of threads that I would like to know to do this without changing the helper functions ajax getGadgets, getDeals, getDeals.

, , N, getGadgets, getDeals getDeals (| N | = 3), -. , initiateChain . M-, | N | ( M).

+5
3

jQuery, .queue ajax, . , dequeue .

function add_api_call_to_queue(qname, api_url) {
    $(document).queue(qname, function() {
        $.ajax({
            type     : 'GET',
            async    : true,
            url      : api_url,
            dataType : 'json',
            success  : function(data, textStatus, jqXHR) {
                // activate the next ajax call when this one finishes
                $(document).dequeue(qname);
            }
        });
    });
}

$(document).ready(function() {

    var queue_name       = 'a_queue';
    var concurrent_calls = 2;

    // add first AJAX call to queue
    add_api_call_to_queue(queue_name, '/example/api/books');

    // add second AJAX call to queue
    add_api_call_to_queue(queue_name, '/example/api/dvds');

    // add third AJAX call to queue
    add_api_call_to_queue(queue_name, '/example/api/shoes');

    // start the AJAX queue
    for (i=0;i<concurrent_calls;i++) {
        $(document).dequeue(queue_name);
    }

})
+14

, ,

var initiateChain = function () {

    var args = arguments,
        index = 0,
        length = args.length,
        process = function ( index ) {

            if ( index < length ) {
                $.ajax({
                    url: '/example.php',
                    complete: function () {
                        // Callbacks get run here
                        args[ index ];
                        process( ++index );
                    }

                });
            }


        };

    if ( length ) {
        process( 0 );
    }

};

initiateChain( getGadgets, getDeals, getDeals );
+1

Thanks @James, I realized that you edited for length. Thus, calls are asynchronous async requests. So the idea is to create the M number of upfront asynchronous calls . Then they will continue these many, when and when each will be completed.

I experimented with nodejs and after initiateChain works as intended

var calls = [];

function initiateChain() {
    var i = 0;
    var maxSteams = 2;
    var tasks = arguments;
    var callback = function () {
      i += 1;
      if (i < tasks.length) {
        tasks[i](callback); //block should call callback when done otherwise loop stops
      }
    }
    if (tasks.length) {
      i = ((tasks.length > maxSteams) ? maxSteams : tasks.length) - 1;
      for (var j = 0; j < maxSteams; j+=1) {
        if (j < tasks.length) {
          tasks[j](callback); //initiate first set
        } else {
          break;
        }
      }
    }
}

//test methods
for(var k = 0; k < 8; k+=1 ) {
  calls[k] = (function (message, index) {
    return function (callback) {
      var ts = new Date().getTime();
      console.log(message + " started - " + ts);
      setTimeout(function() {
        ts = new Date().getTime();
        console.log(message + " completed - " + ts);
        callback();
      }, index * 1000);
    };
  })("call" + (k+1), (k+1))
}

initiateChain(calls[0], calls[1], calls[2], calls[3], 
    calls[4], calls[5], calls[6], calls[7]);

In my experiment, I got the following results

call1 started - 1360580377905
call2 started - 1360580377926

call1 completed - 1360580378937
call3 started - 1360580378937

call2 completed - 1360580379937
call4 started - 1360580379937

call3 completed - 1360580381945
call5 started - 1360580381945

call4 completed - 1360580383946
call6 started - 1360580383946

call5 completed - 1360580386959
call7 started - 1360580386959

call6 completed - 1360580389950
call8 started - 1360580389950

call7 completed - 1360580393972

call8 completed - 1360580397959
0
source

All Articles