Skip to content

Instantly share code, notes, and snippets.

@adrienbrault
Created December 10, 2011 13:00
Show Gist options
  • Select an option

  • Save adrienbrault/1455111 to your computer and use it in GitHub Desktop.

Select an option

Save adrienbrault/1455111 to your computer and use it in GitHub Desktop.
jQuery.ajax with and without deferred
//
// With classic callbacks
//
var callApi = function(success) {
$.ajax({
url: '/hello',
success: function(data) {
// Do callApi stuff here.
// Call the success argument
if (success) success(data)
}
});
}
var callApi2 = function(success2) {
callApi(success: function(data) {
// Do callApi2 stuff here.
// Call the success2 argument
if (success2) success2(data)
});
}
callApi2(function(data) {
// Do external stuff
});
//
// With jQuery.Deferred
//
var callApi = function() {
deferred = $.ajax({
url: '/hello'
});
deferred.done(function(data) {
// Do callApi stuff here.
});
return deferred;
}
var callApi2 = function () {
deferred = callApi();
deferred.done(function(data) {
// Do callApi2 stuff here.
});
return deferred;
}
deferred = callApi2();
deferred.done(function(data) {
// Do external stuff
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment