0

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.

6
  • 2
    What kind of collections - How are you sending the collections - Who is processing the collections? Commented Aug 21, 2013 at 13:35
  • May the site pause rendering while processing? If yes, just do a "synchronus" ajax request Commented Aug 21, 2013 at 13:35
  • @TobSpr That's ridiculous what if the server "suddenly becomes faster"? Unless he's only using 2 collections then I guess it'd be alright Commented Aug 21, 2013 at 13:36
  • Post your processing code. Commented Aug 21, 2013 at 13:38
  • 1
    @Nate I mean something like for (var i = 0;i<5;i++) {$.ajax({async:false, type: "POST", url: "", success: function(msg) {/* process data */}})} Commented Aug 21, 2013 at 13:38

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

There's no need to make the AJAX requests synchronous (as they'll just be JAX requests). Use a callback function that pops the last element out of your array of elements and calls itself when it's done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.