Mastering Web Application

(Rick Simeone) #1
Chapter 3

Promises are first-class JavaScript objects

At first glance it might look like the Promise API adds unnecessary complexity.
But to appreciate the real power of promises we need to see more examples. First
of all we need to realize that promises are first-class JavaScript objects. We can pass
them around as arguments and return them from function calls. This allows us to
easily encapsulate asynchronous operations as services. For example, let's imagine a
simplified restaurant service:


var Restaurant = function ($q, $rootScope) {

var currentOrder;

this.takeOrder = function (orderedItems) {
currentOrder = {
deferred:$q.defer(),
items:orderedItems
};
return currentOrder.deferred.promise;
};

this.deliverOrder = function() {
currentOrder.deferred.resolve(currentOrder.items);
$rootScope.$digest();
};

this.problemWithOrder = function(reason) {
currentOrder.deferred.reject(reason);
$rootScope.$digest();
};
};

Now the restaurant service encapsulates asynchronous tasks and only returns a
promise from its takeOrder method. The returned promise can be then used by
the restaurant customers to hold onto promised results and be notified when results
are available.


As an example of this newly crafted API in action, let's write code that will illustrate
rejecting promises and error callbacks being invoked:


it('should illustrate promise rejection', function () {

pizzaPit = new Restaurant($q, $rootScope);
var pizzaDelivered = pizzaPit.takeOrder('Capricciosa');
Free download pdf