Asynchronous JavaScript using Callbacks

I recently struggled when faced with a problem of using callbacks to handle the asynchronous flow of multiple API calls.

So I figured I’d do a deep dive into callbacks to refresh and solidify my knowledge.  After all, if you want to truly understand something, teach it to someone else!

Functions as First Class Objects

Before we start talking about callbacks, we must first know that JavaScript functions are first-class objects.

Which means what?  And why is that important to a discussion about callbacks?

Being a first-class object in JavaScript means that functions can have properties and methods just like any other object.  Consider this:

It also means that functions can be assigned to a variable.

More importantly for our discussion on callbacks, however, is that because functions are first-class objects, they can be passed to (and returned from) other functions.

This last point, passing functions as arguments to other functions, is the foundation of callbacks.

A callback is simply a function that is passed to another function as an argument, that can then be used (executed) inside that other function.

The previous example used a named function (answer) as the callback. You can (and probably have) also use anonymous functions as callbacks.  This is common when passing callbacks to the native prototype methods for arrays, objects and strings.

Consider the following:

Here we used an anonymous arrow function as our callback to output twice the value of each element.

Now that we know what callbacks are, let’s talk about their use in asynchronous JavaScript.

Understanding ASYNCHRONY

Image of the Police Album - Synchronicity

No, this isn’t what we’re talking about, but the word ‘asynchony’ makes me think of this album…..  Yeah, I know, I’m old…

Before we start talking about controlling asynchronous flow we must first understand the nature of the JavaScript event loop and the fact that it is single threaded. Digging deep into the JavaScript engine is beyond the scope of this post, but understanding the single threaded nature of the event loop is critical to understanding why we need asynchronous code.

For now, think of the event loop as a queue (first in, first out) that executes snippets of your JS code one by one and in the order they were placed in the queue.

Now think of an Ajax request that we might use to get some data from an API.  That Ajax request is costly (in time).  If we place it in the event loop and run it synchronously it will block everything that comes after it while it waits for a response. This affects performance and causes people to leave your site!

In his You Don’t Know JS series, Kyle Simpson describes asynchrony as the difference between now and later, as opposed to parallel, which describes two processes that are executed independent of each other (but possibly at the same time).

This now and later concept is where callback functions come in.  Rather than running that Ajax request from start to finish, blocking all other code execution while we wait, we pass it a callback.

In this scenario, the JS engine can make the Ajax call (now), continue with the event loop, and once the Ajax call returns (later) pass the callback, along with any data it needs from the response, back into the event loop.

Async in action

Let use an example to show what we’re talking about.  For the remaining examples, I’m going to use setTimeout() to simulate async functions, but you can think of it as time spent making an Ajax request.

This example shows asynchronous control of the event loop. Let’s dig deeper in case this isn’t clear.

We’ve defined three functions first, second and delay.

first and second merely log “first” and “second” to the console so we can tell when they’re executed.

delay takes a callback, which it passes to setTimeout(). setTimeout() sets a timer, then calls the function it was passed – in this case, it will call callback after 500 milliseconds.

After the three function definitions, we call delay(first), which puts the function delay() in our event loop.  Upon execution, delay sets a timer for 500 ms, after which, it will call its callback (in this case first()).

Because the timer in setTimeout() is non-blocking, or asynchronous, the event loop is now free to move on to the next snippet of JS, which is our function call to second().

When second is executed, it logs “second” to the console, which is why we see “second” logged to the console before we see “first”, even though delay(first) was called before second().

And finally, after the 500 ms timer elapses, first() is placed in our event loop and executed, which is when “first” shows up in our console.

I’m hoping the example above was simple enough that you could figure it out on your own, otherwise, maybe my long winded explanation helped.

Fun with callbacks and closure

OK, now that we’re pros with callbacks, lets have a little fun with them!

We’re going to use callbacks and closure to set up a four lane race. Granted, it’s only a race in the sense that we’re randomizing the setTimout() time, but it’s fun nonetheless…

Hopefully, the comments in the code clear up how the “race” is being run. If you have any questions, feel free to leave them below.