A promise represents an ongoing task that may either succeed or fail.
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 stepYour 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.
If something is shared across multiple ajax calls, it can be refactored as a new callback and added where required.
$.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.
- Binding to future promises with 'pipe'
- Using Promises in place of callbacks