Phillip Senn
Phillip Senn

Reputation: 47605

How do I know when the last async is done?

I have something like this:

for (var i=0;i<result.qry.ROWCOUNT;i++) {
  myAsync(i);
}

How do I know when all my Async functions have finished executing?

At the risk of someone replying with "Needs more jQuery!", can I use the jQuery promise object? Or deferred or something like that?

Upvotes: 7

Views: 3768

Answers (5)

harpo
harpo

Reputation: 43168

If you are using jQuery, you can also use the ajaxSend and ajaxComplete methods to keep your counter code separate from your dispatch code.

var ajaxPending = 0;

function ajax_changed(indicator, pending) {
    if (pending)
        $(indicator).show();
    else
        $(indicator).hide();
}

$('#loading-indicator').ajaxSend(function() {
    ajax_changed(this, ++ajaxPending);
});

$('#loading-indicator').ajaxComplete(function() {
    ajax_changed(this, --ajaxPending);
});

Upvotes: 1

This is how I would do it:

//Do stuff up here to get records
var rowCount = result.qry.ROWCOUNT, //Save the row count
    asyncCount = 0, //The count of complete async calls
    asyncCallback = function() {
        //To be called whenever an async operation finishes
        asyncCount++; //Increment the row counter
        if (asyncCount >= rowCount) {
            //Do stuff when they're all finished
        }
    };

for (var i=0;i<rowCount;i++) {
  myAsync(i, asyncCallback);
}

function myAsync(index, completeCallback) {
    //Do async stuff with index
    //Call completeCallback when async stuff has finished or pass it
    // into the async function to be called
}

Upvotes: 2

Brent Anderson
Brent Anderson

Reputation: 966

Use a callback function:

for (var i=0;i<result.qry.ROWCOUNT;i++) {
  myAsync(i, myCallback);
}

function myCallback(i){
  //set result.qry.ROWCOUNT to a var somewhere above if it's not available in this scope
  if(i == (result.qry.ROWCOUNT - 1)){
     //now you know you're actually done with all requests
  }
}
function myAsync(i,callback){
  ///do work
  callback(i);
}

Upvotes: -2

Phrogz
Phrogz

Reputation: 303244

Keep track of how many asynchronous calls are outstanding. When each finishes, decrement your counter. When you get to 0, you are in the last callback.

var asyncsLeft = 0;
for (var i=0;i<10;++i){
   asyncsLeft++;
   doSomethingAsyncWithCallback(function(){
     // This should be called when each asynchronous item is complete
     if (--asyncsLeft==0){
       // This is the last one!
     }
   });
}

Due to the single-threaded nature of JavaScript there is no potential race condition where you might get your callback invoked before all of the asynchronous calls have been queued up. It is safe to put the asyncsLeft++ call after the doSomethingAsynchronous, if you like.

Upvotes: 9

Michael Irwin
Michael Irwin

Reputation: 3149

In jQuery, there is the $.ajaxStop function that runs after the last Ajax has ran.

Upvotes: 1

Related Questions