Using jQuery deferred

For some reasons I keep forgetting how to use jQuery deferred objects. Let’s write down some usage examples:

Attaching multiple callbacks to an AJAX request

x = $.getJSON('1.json');x
x.done(function(y){console.log(y)});
x.done(function(y){console.log(y)});
x.done(function(y){console.log(y)});

You can also use $.when, that allows a variable number of deferred objects:

x = $.getJSON('1.json');
$.when(x).then(function(y){console.log(y)});
$.when(x).then(function(y){console.log(y)});
$.when(x).then(function(y){console.log(y)});

Running a callback after multiple AJAX requests

The callback will run when all requests are complete.

$.when($.get('a'), $.get('b'))
 .then(function(a, b) {...});

If the when function receives more than an argument then the callback parameters will be objects like this and not the request content!

  [reponseContent, "success", promiseObject]