Sequential Asynchronous Processing with jQuery Deferreds

Asynchronous processing is one of the most difficult things for devs to understand when switching from the more traditional web programming pattern to a more client-server like model when creating rich JavaScript single-page apps. It involves a lot of passing callbacks around which makes the code ugly to ready and more complex. With the introduction of jQuery Deferred this hasn't to be the case any more!

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:
  1. 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.
  2. An ajax call is done to the server, if the call succeeds, step 3 should be called
  3. The data from the ajax call should be processed and on success the final state should be invoked.
  4. 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 with its ContinueWith etc methods.




Your ad here?