Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steveosoule/6453185 to your computer and use it in GitHub Desktop.
Save steveosoule/6453185 to your computer and use it in GitHub Desktop.
Multiple AJAX Requests - jQuery $.when()
// FROM: http://lostechies.com/joshuaflanagan/2011/10/20/coordinating-multiple-ajax-requests-with-jquery-when/
$.when( getTweets('austintexasgov'),
getTweets('greenling_com'),
getTweets('themomandpops')
).done(function(atxArgs, greenlingArgs, momandpopsArgs){
var allTweets = [].concat(atxArgs[0]).concat(greenlingArgs[0]).concat(momandpopsArgs[0]);
var sortedTweets = sortTweets(allTweets);
showTweets(sortedTweets);
});
var getTweets = function(user){
var url='http://twitter.com/status/user_timeline/' + user + '.json';
return $.get(url, {count:5}, null, 'jsonp');
}
// FROM: http://www.bitstorm.org/weblog/2012-1/Deferred_and_promise_in_jQuery.html
// Example 1
var promise = $.ajax({
url: "/myServerScript"
});
promise.done(myStopAnimationFunction);
promise.done(myOtherAjaxFunction);
// Example 2
var promise1 = $.ajax("/myServerScript1");
var promise2 = $.ajax("/myServerScript2");
$.when(promise1, promise2).done(function(xhrObject1, xhrObject2) {
// Handle both XHR objects
});
promise.done(myShowInfoFunction);
promise.fail(myErrorFunction);
// FROM: http://net.tutsplus.com/tutorials/javascript-ajax/wrangle-async-tasks-with-jquery-promises/
// Example 1
promise.done(function() {
console.log("This will run if this Promise is resolved.");
});
promise.fail(function() {
console.log("This will run if this Promise is rejected.");
});
promise.always(function() {
console.log("And this will run either way.");
});
// Example 2: Shorthand for previous example
promise.then(doneCallback, failCallback, alwaysCallback);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment