When we retrieve data over the network in a single page application,
XMLHttpRequest global object,
implemented natively in all browsers since IE5,
provides the AJAX functions.
Using the raw
XMLHttpRequest object, however, is rather unwieldy,
and in order to avoid having to repeating a lot of cruft code each time
this needs to be done, we use wrapper objects.
AngularJs defines a the
$http module that fills this role,
while EmberJs uses
jQuery's AJAX functions.
That is pretty neat, but callbacks do have their limitations. Imagine if you wanted to do two tasks that are both asynchronous, but need the second one to execute only after the first one has completed. The way to do this would be for the callback function to nest another callback function within itself. If there are three or more things like this, you begin to get some really messy code, characterised by its shape - it looks like a triangle on its side. This known as "callback hell".
Promises overcome this limitation,
by wrapping callback function in promise objects, making it easier to reason
about them in sequences or other types of series and groups.
as the go to means of dealing with asynchronous code.
AngularJs contains its own promise module,
and EmberJs has its own promise library,
Both implementations follow a common specification, the
thus their syntax is almost identical.
∗ The next edition of the ECMAScript specification, ES6 Harmony, includes a proposal for concurrency, and a draft for generators. The latter, generators, has already been implemented in NodeJs, and is due to come to browsers shortly.
We have taken a look at what routing is, and why it continues to be important and relevant in single page applications. We have also looked at the two different ways in which URLs work in single page applications: hash fragments and the HTML5 History API.
Finally we have taken a look at the concept of state machines, and the crucial role that they play in enabling routing in both AngularJs and EmberJs. These frameworks use different types of state machines - finite and hierarchical. impacts the routing functionality that each can support, and we will examine this in greater detail in the next article.