Created
December 10, 2011 13:00
-
-
Save adrienbrault/1455111 to your computer and use it in GitHub Desktop.
jQuery.ajax with and without deferred
This file contains hidden or 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
| // | |
| // 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