Skip to content

Instantly share code, notes, and snippets.

@akshaye
Created January 25, 2013 11:37
Show Gist options
  • Select an option

  • Save akshaye/4633756 to your computer and use it in GitHub Desktop.

Select an option

Save akshaye/4633756 to your computer and use it in GitHub Desktop.
Things i learned while reading Async Javascript

A promise represents an ongoing task that may either succeed or fail.

Promises and Deferreds

A promise exposes methods to attach handlers but not ones that change the state. Deferred is a superset of Promise - with methods to change its state. Idea is to create a Deferred and then pass its Promise around the app, which is available by calling Deferred.Promise() method. This prevents other pieces from interfering with its state while enabling them to perform any action in response to change in deferred. All Ajax functions in jQuery return Promises, starting from v1.5.

resolve -> done
reject -> fail
notify -> progress
then - shorthand for adding all 3 (done, fail, progress) callbacks in one step

Advantages

Encapsulation

Your application may want to do multiple, possibly unrelated, things in response to an Ajax call. Instead of handling everything in one humongous callback, it's much more elegant to pass a Promise around the app. Callbacks can be added even when the promise is in resolved/rejected state - they will execute immediately.

DRY

If something is shared across multiple ajax calls, it can be refactored as a new callback and added where required.

Joining Promises

$.when(firstPromise, secondPromise)
  .then(onBothPass, onAnyFail)

when acts as a logical AND for promises. Resulting promise is resolved when all given promises are resolved, or rejected when any of the given promises is rejected. So in above code, onBothPass will run if both promises get resolved, or onAnyFail will run if either gets rejected.

Advanced topics

  • Binding to future promises with 'pipe'
  • Using Promises in place of callbacks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment