Communicating with a Back-end Server
pizzaDelivered.then(pawel.eat, pawel.beHungry);
pizzaPit.problemWithOrder('no Capricciosa, only Margherita
left');
expect($log.warn.logs).toContain(['Pawel is hungry because: no
Capricciosa, only Margherita left']);
});
Aggregating callbacks
One promise object can be used to register multiple callbacks. To see this in practice
let's imagine that both authors of this book are ordering a pizza and as such both are
interested in the delivered order:
it('should allow callbacks aggregation', function () {
var pizzaDelivered = pizzaPit.takeOrder('Margherita');
pizzaDelivered.then(pawel.eat, pawel.beHungry);
pizzaDelivered.then(pete.eat, pete.beHungry);
pizzaPit.deliverOrder();
expect($log.info.logs).toContain(['Pawel is eating delicious
Margherita']);
expect($log.info.logs).toContain(['Peter is eating delicious
Margherita']);
});
Here multiple success callbacks are registered and all of them are invoked upon
a promise resolution. Similarly, promise rejection will invoke all the registered
error callbacks.
Registering callbacks and the promise lifecycle
A promise that was resolved or rejected once can't change its state. There is only one
chance of providing promised results. In other words it is not possible to:
- Resolve a rejected promise
- Resolve an already resolved promise with a different result
- Reject a resolved promise
- Reject a rejected promise with a different rejection reason
Those rules are rather intuitive. For example, it wouldn't make much sense if we
could be called back with the information that there are problems with our order
delivery after our pizza was successfully delivered (and probably eaten!).