jQuery Deferreds have been introduced with jQuery v1.5 and are a really nice mechanism for handling such asynchronous processing situations. Such asynch processing does not necessarily have to be an ajax call, but might also involve some operation that waits for an external event, such as a user interaction.
For instance consider the following control flow:
- The user clicks a button.
A popup should appear asking the user for some information. If he provides the info, step 2 should be called.
- An ajax call is done to the server, if the call succeeds, step 3 should be called
- The data from the ajax call should be processed and on success the final state should be invoked.
- The final success state.
Obviously, if in any of those states the operation fails or the user cancels the operation, the final state should never be reached, but rather some failure state should be called.
How would you implement this? With callbacks? A nightmare...I'm not even going to implement it as the result would be totally unreadable, not to speak about maintainability of the code. Instead, with the jQuery Deferred object, the result might look as shown in this dummy jsfiddle example:
Note, I consciously didn't properly refactor the code in order to not "hide" anything for the purpose of this demonstration here.
This reminds me a bit of the C# Task API
etc methods. References:http://msdn.microsoft.com/en-us/scriptjunkie/gg723713.aspx