$.Deferred and Promise
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.
- The article by Jeremy Chone, at http://www.html5rocks.com/en/tutorials/async/deferred/
- 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:
- Example #1 – calling getData1 to obtain an integer using Promise.done & Promise.fail
- Example #2 – calling getData2 to obtain an integer using $.when and Promise.then
- Example #3 – calling getData3, getData4 in parallel to obtain 2 integers using $.when and then summing the 2 returned integer values using Promise.done
- 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.