Deferred / Promise pattern using jQuery
Daniel Demmel | @daaain
ustwo™ design studio | ustwo.co.uk
Daniel Demmel | @daaain
ustwo™ design studio | ustwo.co.uk
resolve()
d or reject()
edpending
state, can only be finished oncestate()
), but completely immutable so no interface for resolutiondone()
and fail()
then()
(used to be pipe()
)$.when()
Setting up a listener and triggering it with resolve
A resolved Deferred will still trigger the callback
Return a Promise from a method and attach a listener to it (can have more than one)
Create a Promise for DOM ready and the two AJAX requests and wait for all of them to be fulfilled
The AJAX request can be already fired off while we wait for the DOM (using chained listeners with then()
)
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!
then()
and done()
then()
is chainable, but is less performant as it has to create a new Promise to return.done()
is a simple callback and can register multiple handlers with it, but doesn't handle failure (you'll need to attach a fail()
too).then()
s mid-chain and close it off with done()
and fail()
.notify()
and progress()
always()
for catching all outcomesthen()
chain
/