Deferred / Promise pattern using jQuery

Daniel Demmel | @daaain
ustwo™ design studio | ustwo.co.uk

A convoluted example

image

http://jsfiddle.net/dain/87uPV/3

Why?

Asynchronous spaghetti

Timing

What?

Deferred

Promise

How?

Canonical Deferred

Setting up a listener and triggering it with resolve

Canonical Deferred post-resolve

A resolved Deferred will still trigger the callback

Canonical Promise + When

Return a Promise from a method and attach a listener to it (can have more than one)

Untangle our example

Create a Promise for DOM ready and the two AJAX requests and wait for all of them to be fulfilled

Another solution

The AJAX request can be already fired off while we wait for the DOM (using chained listeners with then())

Dealing with rejection

When a Promise gets reject()ed it will immediately cascade down the then() chain

Example from Domenic Denicola's blog post "You're Missing the Point of Promises", go and read it now!

More?

When to use then() and done()

More?

Even more?

#

/