IT:AD:Promise

Summary

A Promise is a deferred action.

THere's nothing inherently wrong will callbacks – just that they get a bit unwieldy when things get complex.


doSomethingThatWill = function(data,callback){
    if (doWhatever){
       if (successCallback){successCallback()}
    }else{
       if (errorCallback){errorCallback()}
    }
}

Just that it can be easier…

  • Deferred
    • A proxy for an asynchronous, future event
    • Has an interface for getting resolve()d or reject()ed
    • Starts in pending state, can only be finished once
    • Calls listeners immediately (but always async) once resolved
  • Promise
    • Allows listening and state inspection (using state()), but completely immutable so no interface for resolution
    • jQuery specific listeners are done() and fail()
    • Can be chained with then() (used to be pipe())
    • Can be grouped and processed using $.when()