Mastering Web Application

(Rick Simeone) #1
Chapter 3

The other scenario that we should consider is re-throwing exceptions as it might
happen that recovery won't be possible. In such a case the only option is to trigger
another error and the $q service has a dedicated method ($q.reject) for this purpose:


it('should illustrate explicit rejection in chain', function () {

var explain = function(reason) {
return $q.reject('ordered pizza not available');
};

pizzaPit.takeOrder('Capricciosa')
.then(slice, explain)
.then(pawel.eat, pawel.beHungry);

pizzaPit.problemWithOrder('no Capricciosa, only Margherita
left');

expect($log.warn.logs).toContain(['Pawel is hungry because:
ordered pizza not available']);
});

The $q.reject method is an equivalent of throwing an exception in the
asynchronous world. This method is returning a new promise that is rejected
with a reason specified as an argument to the $q.reject method call.


More on $q

The $q service has two additional, useful methods: $q.all and $q.when.


Aggregating promises


The $q.all method makes it possible to start multiple asynchronous tasks and be
notified only when all of the tasks complete. It effectively aggregates promises from
several asynchronous actions, and returns a single, combined promise that can act as
a join point.


To illustrate usefulness of the $q.all method, let's consider an example of ordering
food from multiple restaurants. We would like to wait for both orders to arrive
before the whole meal is served:


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

var ordersDelivered = $q.all([
pizzaPit.takeOrder('Pepperoni'),
saladBar.takeOrder('Fresh salad')
Free download pdf