Ricardo Tealdi blog

Yet another tech blog

Handling multiple ajax requests callbacks with jQuery.when

| Comments

Over the last days, my team have been working on a front-end project.

We’ve implemented two ajax requests, inside a collapsing box content, that needed to fade out a single spinner loader when both requests had finished.

Our first thought was to try to code this handling, hiding the spinner only when both requests finishes and storing the requests status data on HTML DOM or on Javascript global variables.

But, wait a minute. Thinking on the DRY concept, maybe someone has already done this job for us.

After googling a little, we’ve found that jQuery already done it. I’m talking about the jQuery.when method.

This was exactly what we were looking for. Its usage is really simple:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var mySpinner = {
  hide : function () {
    jQuery('#my-spinner-id').hide();
  }
};

jQuery.when(
  jQuery.ajax("/first"),
  jQuery.ajax("/second"),
  "any-other-javascript-object")
.then(
  mySpinner.hide,  // yourSuccessFunction
  mySpinner.hide); // yourFailureFunction
});

As you could see, you only need to pass the ajax requests as parameters to jQuery.when (even if one of them is not a jQuery ajax request), and the success and failure callback functions to .then method.

Doing only this, jQuery will handle your requests for you and will execute the callbacks after all requests have been finished.

So, we’ve decided to use this jQuery implementation to handle the ajax requests. So far, it is meeting our expectations.

Comments