Mastering Web Application

(Rick Simeone) #1

Communicating with a Back-end Server


pawel.beHungry);

pizzaPit.problemWithOrder('no Capricciosa, only Margherita
left');
expect($log.warn.logs).toContain(['Pawel is hungry because: no
Capricciosa, only Margherita left']);
});

Here the rejection result from the restaurant is propagated up to the person
interested in the final result. This is exactly how the exception handling works in the
synchronous world: a thrown exception will bubble up to a first catch block.


In the Promise API the error callbacks act as catch blocks, and as with standard catch
blocks - we've got several options of handling exceptional situations. We can either:



  • recover (return value from a catch block)

  • propagate failure (re-throw an exception)


With the Promise API it is easy to simulate a recovery in catch block. As an example,
let's assume that our hosts will take an effort of ordering another pizza if a desired
one is not available:


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

var retry = function(reason) {
return pizzaPit.takeOrder('Margherita').then(slice);
};

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

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

expect($log.info.logs).toContain(['Pawel is eating delicious sliced
Margherita']);
});

We can return a new promise from an error callback. The returned promise will be
part of the resolution chain, and the final consumer won't even notice that something
went wrong. This is a very powerful pattern that can be applied in any scenario
that requires retries. We are going to use this approach in Chapter 7, Securing Your
Application, to implement security checks.

Free download pdf