Last active
July 2, 2017 20:53
-
-
Save terrymun/c49d646b01c4ed3143bf to your computer and use it in GitHub Desktop.
Better $.ajax requests—using an array of returned deferreds
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
// 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 | |
}); | |
}); |
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
// 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