Search code examples
javascriptarrayscontrol-flow

In Javascript, process list synchronously


I have a given collection of items to be processed; each item must wait for the completion of the previous one.

By collection of items I mean an array of integer values.

By "processing" I mean make a POST to a HTTP server, passing the integer value of each array element.

I've found something that looks like waht I'm looking for: doSynchronousLoop.js but I wonder if there are alternatives.


Solution

  • If your site may pause rendering while doing the requests, here's a solution with jQuery:

    // process 5 items
    for (var i = 0; i< 5; i++) {
       // ajax request done with jquery
       $.ajax({
          async: false, /* this makes it execute synchronously */
          url: "the url to handle item #i",
          type: "POST",
          success: function(msg) {
              // process data for item #i
          } 
       })
    }
    

    Edit: you can solve it asynchronously, too:

    items = [put your items here]
    current_item = 0
    
    function processItem() {
        if (current_item == items.length) {
          // list processing finished
          return;
        }
    
        $.ajax({
          async: true,
          url: "the url to handle item #current_item",
          type: "POST",
          success: function(msg) {
              // process data for item #current_item
              processItem();
              current_item++;
          } 
       })
    
    }
    

    Don't miss to put the variables in a scope, I just left them in global scope to make the example easier to understand.

    See also the docs: jQuery.ajax