Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best solution to wait for all ajax callbacks to be executed

Imagine we have to sources to be requested by ajax. I want to perform some actions when all callbacks are triggered. How this can be done besides this approach:

(function($){
  var sources = ['http://source1.com', 'http://source2.com'],
  guard = 0, 
  someHandler = function() { 
    if (guard != sources.length) { return; }
    //do some actions
  };

  for (var idx in sources) {
    $.getJSON(sources[idx], function(){ guard++; someHandler(); })
  }
})(jQuery)

What I don't like here is that in this case I can't handle response failing (eg. I can't set timeout for response to come) and overall approach (I suppose there should be a way to use more power of functional programming here)

Any ideas?

Regards!

UPD: Thanks for solution with chaining callbacks. I found a good approach here:. this is what was proposed in comments:

(function hidenext(jq){
    jq.eq(0).fadeOut("fast", function(){
        (jq=jq.slice(1)).length && hidenext(jq);
    });
})($('div#bodyContent a'))

With a little bit of tweaking it can wait for the last callback.

Now I want to handle properly long running requests. Any clues?

like image 765
glaz666 Avatar asked May 28 '10 10:05

glaz666


1 Answers

Duplicate of javascript: execute a bunch of asynchronous method with one callback

function createCallback(limit, fn){
    var finishedCalls = 0;
    return function(){
        if (++finishedCalls == limit){
             fn();
        }
    };
}


var callback = createCallback(4, function(){
    alert("woot!");
});


async1(callback);
async2(callback);
async3(callback);
async4(callback);
like image 78
Sean Kinsey Avatar answered Oct 20 '22 00:10

Sean Kinsey