When I deal with async, I go promises (deferred). This is the most “promising” approach which make your code reusable and predictable without fall into callback hell.
I would like to share you some useful techniques how to promise well. (Those examples are implementing with Jquery deferred but it can apply to any other implementaion.)
User behavior as promise
Your code might need some user input before it executes next step. So make those user behaviors as promises and use .then() to solve them sequentially or $.when to aggregate them together. Good for certain type of UI such as DIALOG, PROMPT, FORM, STEPS.
Mixing multiple ajax responses into one
I usually make my remote data resource as function return promise. Then I don’t need to define success callback at the beginning. Just chain with .then(callback) afterward. It really gives me lot more flexibility , meanwhile eliminating code duplication e.g. url, ajax config, you will find out only data params will changed in most cases.
If you want to mix different resources together. here comes your best friend $.when. In this example, I fetch posts and comments and mixing the comment into each post entry. The aggregation call can even combine with other call again. Think about the extensibility!
TIPS: $.ajax return jqxhr which is similar to $.deferred you can use .then for callback or $.when for aggregation. However, the response will be an array when you use $.when. It won’t be the typical response you get.
Caching ajax calls
The fulfilled promise can chain with .then() to trigger the callback immediately. So it’s a good idea to cache the previous ajax request (which return a promise). You can reuse the cache later without calling server multiple times for the same data.
Because you always expect the call will return promise so simply chaining .then() everywhere to ensure code consistency. If you need fresh new data, clear the cache or call the fetcher with forceUpdate equal true.
You may never heard of those techniques above or already used them widely in your code. Anyway, I hope those can help you rethink “How to promise well?” Let’s say goodbye to callback hell :)