Mastering Web Application

(Rick Simeone) #1

Communicating with a Back-end Server


]);

ordersDelivered.then(pawel.eat);

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

The $q.all method accepts an array of promises as its argument, and returns an
aggregated promise. The aggregated promise will be resolved only after all the
individual promises are resolved. If, on the other hand, one of the individual actions
fail the aggregated promise will be rejected as well:


it('should illustrate promise aggregation when one of the promises
fail', function () {

var ordersDelivered = $q.all([
pizzaPit.takeOrder('Pepperoni'),
saladBar.takeOrder('Fresh salad')
]);

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

pizzaPit.deliverOrder();
saladBar.problemWithOrder('no fresh lettuce');
expect($log.warn.logs).toContain(['Pawel is hungry because: no fresh
lettuce']);
});

The aggregated promise gets rejected with the same reason as the individual promise
that was rejected.


Wrapping values as promises


Sometimes we might find ourselves in a situation where the same API needs to work
with results obtained from asynchronous and synchronous actions. In this case it is
often easier to treat all the results as asynchronous.


The $q.when method makes it possible to wrap a JavaScript object
as a promise.
Free download pdf