Mastering Web Application

(Rick Simeone) #1
Chapter 3

Continuing our "pizza and salad" example, we could imagine that a salad is ready
(synchronous action) but a pizza needs to be ordered and delivered (asynchronous
action). Still we want to serve both dishes at the same time. Here is an example
illustrating how to use the $q.when and the $q.all methods to achieve this in a very
elegant way:


it('should illustrate promise aggregation with $q.when', function () {

var ordersDelivered = $q.all([
pizzaPit.takeOrder('Pepperoni'),
$q.when('home made salad')
]);

ordersDelivered.then(pawel.eat, pawel.beHungry);

pizzaPit.deliverOrder();
expect($log.info.logs).toContain(['Pawel is eating delicious
Pepperoni,home made salad']);
});

The $q.when method returns a promise that is resolved with a value supplied
as an argument to the when method call.


$q integration in AngularJS


The $q service is not only a quite capable (yet lightweight!) Promise
API implementation, but also it is tightly integrated with the AngularJS
rendering machinery.


Firstly, promises can be directly exposed on a scope and rendered automatically
as soon as a promise is resolved. This enables us to treat promises as model values.
For example, given the following template:


<h1>Hello, {{name}}!</h1>

And the code in a controller:


$scope.name = $timeout(function () {
return "World";
}, 2000);

The famous "Hello, World!" text will be rendered after two seconds without any
manual programmer's intervention.

Free download pdf