0

I am using custom triggered events after asynchronous calls happen, and I need a way to determine when they've ALL been triggered.

For example:

var ajaxFunction1 = function(){
    $.ajax({
        url: "someUrl.html",
        complete: function(){
            //Ok, all done
            $(document).trigger('ajaxFunction1Finished')
        }
    })
}

var ajaxFunction2 = function(){
    $.ajax({
        url: "someUrl.html",
        complete: function(){
            //Ok, all done
            $(document).trigger('ajaxFunction2Finished')
        }
    })
}

var ajaxFunction3 = function(){
    $.ajax({
        url: "someUrl.html",
        complete: function(){
            //Ok, all done
            $(document).trigger('ajaxFunction3Finished')
        }
    })
}

ajaxFunction1();
ajaxFunction2();
ajaxFunction3();

jQuery
   .when( /* Whenever $(document) receives those three events */ )
   .done(function(){
      //Do something
   })

Is this possible? I'd like to avoid triggering new events just to get a return true.

Jake
  • 4,014
  • 8
  • 36
  • 54
  • maybe this can help you http://stackoverflow.com/questions/4368946/javascript-callback-for-multiple-ajax-calls – Faton Sep 20 '13 at 19:01

2 Answers2

0

This may help -

var requestCompletedArray = [];

/* assuming i have `n` ajax calls to make */
for(var i = 0; i < n; i++) {
    $.ajax({
        url: "someUrl.html",
        complete: callback
    })
}

/* my callback definition */
function callback(data) {
    if(requestCompletedArray.length < n-1) {
        requestCompletedArray.push(data.status);
        return;
    } else if(requestCompletedArray.length === n-1) {
        //do something, all requests are completed
    } else {
        return;
    }
}
Moazzam Khan
  • 3,130
  • 2
  • 20
  • 35
  • This would work for the example code I posted, true. However, I need to be able to avoid the case where one of the events is triggered twice. In other words, your solution works, but only if I can guarantee that each triggered event gets triggered only once. – Jake Sep 20 '13 at 19:05
0

Are the triggers doing anything special?

var oneDone = false;
var twoDone = false;
var threeDone = false;

function checkIfEverythingIsDone() {
   if (oneDone && twoDone && threeDone) {
     // everything is done and you may proceed
   }
}

var ajaxFunction1 = function(){
  $.ajax({
    url: "someUrl.html",
    complete: function(){
      oneDone = true;
      checkIfEverythingIsDone();
    }
  })
}

var ajaxFunction2 = function(){
  $.ajax({
    url: "someUrl.html",
    complete: function(){
      twoDone = true;
      checkIfEverythingIsDone();
    }
  })
}

var ajaxFunction3 = function(){
  $.ajax({
    url: "someUrl.html",
    complete: function(){
      threeDone = true;
      checkIfEverythingIsDone();
    }
  })
}

ajaxFunction1();
ajaxFunction2();
ajaxFunction3();
mikekavouras
  • 220
  • 2
  • 8