Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Callbacks are dead

Callbacks are dead

An intro to $.Deferred()

Avatar for hacknightly

hacknightly

August 02, 2012
Tweet

Other Decks in Programming

Transcript

  1. Deferreds are new as of jQuery 1.5 and help to

    separate the logic dependent on the outcome of a task from the task itself. They are now built into $.ajax() Your old-school AJAX requests :
  2. Can now operate with greater flexibility: Why is this awesome?

    1. We are no longer limited to a single success, error, or complete handler. 2. Instead of simple callbacks, these hooks are now self-managed FIFO callback queues. 3. Callbacks may be attached even AFTER an AJAX request – or any observable task – has completed.
  3. Can this get more awesome? YES. Here’s a scenario where

    we want to call a function only after several concurrent AJAX calls have been completed. Old-School (and hacky)
  4. New-school and full of hotness: INTRODUCING…… $.when() – deferred’s little

    helper. Q: How does this work? A: All AJAX methods now return an object containing a “promise”. This is a read-only view into the result of the task. $.when() waits for all requests to execute, and once they do, callbacks attached will fire as appropriate (depending on the success/fail state of the task)
  5. There are a bunch of awesome methods available to you

    when working with deferreds. Methods available to all deferreds (AJAX, $.when(), and manual): It’s also important to note that you don’t have access to all of the properties of the deferred object. Only the promise, callback-binding methods, and the isRejected() and isResolved() methods to check a deferred’s state.
  6. Creating your own Deferred: Q : “Yeah, so $.ajax() and

    $.when() are performing all of this magic. Can I perform a bit by hand?” A : YES.
  7. Wrap-Up 1. Deferreds are amazing, and introduce a new, robust

    approach to writing asynchronous tasks. 2. Old school callbacks limit us to single success, error, and complete methods. Deferreds let us structure our flow how we see fit. 3. No longer have to worry about queuing and de queuing of callbacks.