Skip to content

Instantly share code, notes, and snippets.

@terrymun
Last active July 2, 2017 20:53
Show Gist options
  • Save terrymun/c49d646b01c4ed3143bf to your computer and use it in GitHub Desktop.
Save terrymun/c49d646b01c4ed3143bf to your computer and use it in GitHub Desktop.
Better $.ajax requests—using an array of returned deferreds
// Let's say we have a click handler and fires off a series of AJAX request
$selector.on('click', function() {
// Construct empty array
var deferreds = [];
// Loop using .each
$(this).find('div').each(function() {
var ajax = $.ajax({
url: $(this).data('ajax-url'),
method: 'get'
});
// Push promise to 'deferreds' array
deferreds.push(ajax);
});
// Use .apply onto array from deferreds
$.when.apply($, deferreds).then(function() {
// Things to do when all is done
});
});
// Let's say we have a click handler and fires off a series of AJAX request
$selector.on('click', function() {
// Map returned deferred objects
var deferreds = $(this).find('div').map(function() {
var ajax = $.ajax({
url: $(this).data('ajax-url'),
method: 'get'
});
return ajax;
});
// Use .apply onto array from deferreds
// Remember to use .get()
$.when.apply($, deferreds.get()).then(function() {
// Things to do when all is done
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment