Created
October 3, 2012 03:28
-
-
Save jayliew/3824822 to your computer and use it in GitHub Desktop.
jQuery example: Array of Deferreds and When / Then
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var dfd_arr = []; // array of deferred objects | |
var get_dfd1 = function(){ | |
var dfd1 = $.Deferred(); | |
var req = $.ajax({ | |
success: dfd1.resolve, | |
}); | |
req.done(function(){ // dfd1 success callback | |
console.log('dfd1 done'); | |
var get_dfd2 = function(){ | |
var dfd2 = $.Deferred(); | |
var req2 = $.ajax({ | |
success: dfd2.resolve, | |
}); // ajax | |
req2.done(function(){ // dfd2 success callback | |
console.log('dfd2 done'); | |
}); | |
return dfd2.promise(); | |
}; // get dfd2 | |
// Push as many of these Deferreds onto the array. | |
// Important: it's get_dfd2(), not get_dfd2, that is pushed. | |
// $.when() takes an array of Deferreds, not array of functions | |
dfd_arr.push(get_dfd2()); | |
}); // end dfd2 success callback | |
return dfd1.promise(); | |
}; // get dfd1 | |
$(function(){ | |
$.when(get_dfd1()).then(function(data){ | |
console.log('outer when callback') | |
// note the use of .apply() here | |
$.when.apply($, dfd_arr).then(function(){ | |
console.log('inner when callback'); | |
}); // inner when | |
}); // outerwhen | |
}); // on dom load |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment