Monthly Archives: January 2013

A Much Better Way To Do Callbacks

$.Deferred and Promise

The traditional way of dealing with callbacks in JavaScript can often yield unreadable and hard to maintain code. jQuery’s Deferred ($.Deferred), a chainable utility object first introduced in v1.5, can be used to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function. Using $.Deferred and Promise can eliminate many of the negatives often associated with cascading callback functions.

Rather than writing a full tutorial I thought it would be better to provide you with real working examples using $.Deferred and Promise which cover various use cases. The code in my repo is well documented and simple working code that you can clone from GitHub at github.com/jeffschwartz/jQueryDeferred and explore on your own using just your browser and a simple code editor.

If you have not yet been exposed to $.Deferred and Promise I recommend you read the 2 articles I mention below as well as jQuery’s own documentation, located at http://api.jquery.com/category/deferred-object/. These 3 resources should provide you with a solid foundation and understanding of $.Deferred and Promise which will make following my code much easier.

  1. The article by Jeremy Chone, at http://www.html5rocks.com/en/tutorials/async/deferred/
  2. The article by Julian Aubourg and Addy Osmani, at http://msdn.microsoft.com/en-us/magazine/gg723713.aspx

Includes 4 Examples and a Test Suite

The code comes with 4 examples covering 4 use cases, which are:

  1. Example #1 – calling getData1 to obtain an integer using Promise.done & Promise.fail
  2. Example #2 – calling getData2 to obtain an integer using $.when and Promise.then
  3. Example #3 – calling getData3, getData4 in parallel to obtain 2 integers using $.when and then summing the 2 returned integer values using Promise.done
  4. Example #4 – calling getData5, getData6 in parallel to obtain 2 integers using $.when and then calling getSum using Promise.then to sum the 2 returned integer values and obtaining the result using Promise.done

In addition to the 4 examples, a full test suite that includes 7 tests, one for each mock api function, is also included and it uses QUnit. To run the tests open the test/qunit.html file in your browser.

Comments are appreciated as always.

:q