The Asynchronous Nature of JavaScript

JavaScript is a quirky language that has the ability to frustrate you to no end if you don't know about certain features. This is going to be the first of many posts about JavaScript tips and quirks, and will be focused on the asynchronous nature of JavaScript.

First let's look at this block of Python:

import urllib2
content = urllib2.urlopen(some_url).read()
print content

The last line there will print the entire response receive from some_url. Each one of these lines is guaranteed to execute in order, and print content will wait to execute until after read() is done receiving data from some_url.

JavaScript is not quite that simple. Python scripts don't have users triggering actions all of the time that need to be responded to as soon as possible, which is something that happens frequently in JavaScript.

When you go to a news website, say CNN, you are likely bombarded by ads unless you are running an ad blocker. If CNN was running on Python in your browser, your page would freeze up repeatedly while all of the images loaded for the pages and ads, and you would not be able to click on anything until after the page was totally loaded. If the page loaded a lot in the background it could be a while before you're able to interact with the page at all, which would be super inconvenient.

Enter JavaScript. JavaScript is an asynchronous language, which means code (generally) wont block the next line of code from executing if it takes a while. Let's look at a block of code that also does a GET request, but this time in JavaScript.

console.log(1);
$http.get(some_url, (data) => {
    console.log(2);
});
console.log(3);

If this code executed in the order it was written, we would see 1 2 3 printed into the console. But this is JavaScript. It doesn't execute code in order if something is going to take some time and uses a callback like $http.get above. Instead you will see 1 3 2 printed in your console, because JavaScript will continue executing the rest of your code while it waits for $http.get to finish what it is doing. Then $http.get calls its callback (that (data) -> guy) and the code in the callback will execute using the data it just got from some_url.

In the right hands, asynchronous languages can be incredibly powerful, but if you don't know the ins and outs you will be sure to trip up occasionally. You're going to want to be very careful to avoid Callback Hell, which occurs when you have lots of nested callbacks and the code becomes hard to read and even harder to maintain. That will be the topic of another blog though.