Understanding How Asynchronous Requests Work

If you’ve done any JavaScript programming, you are familiar with callbacks. These are functions that get called later. The simplest example is setTimeout, which takes a callback function and a number of milliseconds. After the given milliseconds have elapsed, the function is called.

In this code, we execute the function errorMessage one second later:

 var​ errorMessage = ​function​() {
  alert(​"OH NOES!"​);
 };
 setTimeout(errorMessage,1000);

We also saw this when using $http in Chapter 5, Build a Dynamic UI with AngularJS, where we passed a callback to get that would execute our code once we got a response from the server. We didn’t really talk about why $http works that way. Now we will. ...

Get Rails, Angular, Postgres, and Bootstrap now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.