jQuery Deferred/Promise Design Patterns and use cases

design-patterns, javascript, jquery, jquery-deferred, oop

Solution

In which situations is a solution using jQuery Deferred called for

I think that as a thumb rule, every time you have both

- one or more asynchronous tasks

- some related callbacks depending on the success/fail of those task

you can try to refactor your code in terms of deferred objects and promises. Most common scenarios in which deferred objects could be used at best involve

- An Ajax request and callback/s (a single request, parallel or chained requests)

- An asynchronous loading of assets and actions to perform at `load` event (e.g. an image preloader like this one: https://gist.github.com/958683)

- A callback to execute after complete of an animation or a lot of sequential animations which would require a lot of nested scopes: this can be easily achieved just chaining a `promise()` method to the `animate()` method so to return a promise to handle with `done()` callback (to be honest I cannot really figure out how an animation can fail)

hope this hint could be useful in some way.

Problem

My question is quite general and some related questions can be found on SO, but none of those really are what I am looking for. I have been reading up on/toying with the jQuery Deferred object and I see it is used a lot inside the library itself to handle ajax requests and animation etc. I understand the general functionality and think it has proven to be very useful in some situations. The jQuery library solves some problems quite elegantly using this concept. Now my question is: I think it would be very useful to have an overview of distinct problem/solution scenarios that can be solved elegantly and robustly using the Deferred object. In which situations is a solution using jQuery Deferred called for? Which general patterns in javascript software design can be distinguished that can be solved most elegantly using jQuery Deferred functionality? I'm aiming to compile a list of quite general patterns (as opposed to very specific examples), in the spirit of the gang of four design patterns every OO analyst knows about. With such a list in the back of the head, when designing jQuery solutions it should become second nature to take advantage of these deferred patterns in just the same way the bridge, factory, ... patterns already help us to design flexible and robust solutions without having to re-invent the wheel every time.

Original source