Promises

in Angular JS


What is a Promise?



A promise represents the result of
an asynchronous operation

AN async Experience


JS Async Operations


setTimeout/setInterval
XmlHttpRequest (AJAX)


Web Workers
Element Creation/OnLoad
Generators

Promise Facts

  • A Promise represents a task that will finish in the future
  • A Promise is a representation of an asynchronous activity
  • A Promise is an instance with three methods
    • then()
    • catch()
    • finally()
  • A Promise will eventually be resolved or rejected


A promise is in one of three different states
 

* Immutable 

AngularJS Deferred API

Implemented using the $q service

Typical Use Case

function myPromise() {
    var deferred = $q.defer();

    doSomethingAsync( function( result ) {
        deferred.resolve( result );
    } );

    return deferred.promise;
}

AngularJS Promise API

Result of deferred.promise

var p = myPromise();

    p.then( success, error, notify )
    p.catch( error )    
    p.finally ( callback )

Code Examples


GitHub:  github.com/Transcordia/ng-meetup

Promises

By James Cook

Promises

  • 1,000