Implement callback on completion of multiple asynchronous functions

Lets say, you need to execute a function 'myCallback' after completion of 2 async functions apiCall1 and apiCall2. Following is how you can implement this. Lets define the 2 async functions first:
var apiCall1 = function(){
 var complete1 = $.Deferred();
 $.ajax({
  url: '/url1',
  success: function(){
   successHandler1();
   complete1.resolve();
  }
 });
 return complete1.promise();
}
var apiCall2 = function(){
 var complete2 = $.Deferred();
 $.ajax({
  url: '/url2',
  success: function(){
   successHandler2();
   complete2.resolve();
  }
 });
 return complete2.promise();
}
Here is how you can define 'myCallback':
var myCallback = function(){
 //do something
}
$.when(apiCall1, apiCall2).done(myCallback);
Check out a working sample on JSFiddle.

References:

No comments:

Post a Comment