Mastering Web Application

(Rick Simeone) #1

Communicating with a Back-end Server


The sample SCRUM application described in this book relies on
the node.js server configured in a way that it proxies calls to the
MongLab REST APIs.

The promise API with $q


JavaScript programmers are accustomed to the asynchronous programming model.
Both a browser and the node.js execution environments are full of asynchronous
events: XHR responses, DOM events, IO and timeouts, which can be triggered
at any moment and in random order. Even if, we are all used to coping with the
asynchronous nature of the execution environment the truth is that asynchronous
programming might be perplexing, especially when it comes to synchronizing
multiple asynchronous events.


In the synchronous world chaining function calls (invoking a function with a result of
another function) and handling exceptions (with try/catch) is straightforward. In the
asynchronous world, we can't simply chain function calls; we need to rely on callbacks.
Callbacks are fine when dealing with just one asynchronous event, but things start
to get complicated as soon as we need to coordinate multiple asynchronous events.
Exceptional situation handling is particularly tough in this case.


To make asynchronous programming easier the Promise API was recently adopted
by several popular JavaScript libraries. The concepts behind the Promise API are not
new, and were proposed in the late seventies, but only recently those concepts made
it into the mainstream JavaScript programming.


The main idea behind the Promise API is to bring to the asynchronous
world the same ease of functions calls chaining and error handling as
we can enjoy in the synchronous programming world.

AngularJS comes with the $q service a very lightweight Promise API
implementation. A number of AngularJS services (most notably $http, but also
$timeout and others) heavily rely on the promise-style APIs. So we need to get
familiar with $q in order to use those services effectively.


The $q service was inspired by the Kris Kowal's Q Promise API library
(https://github.com/kriskowal/q). You might want to check
out this library to gain a better understanding or promise concepts
and compare AngularJS lightweight implementation with the full
featured Promise API library.
Free download pdf