Sitemap
Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Asynchronous JavaScript

Not so single-threaded.

10 min readApr 4, 2020

--

Press enter or click to view image in full size
Single-threaded? Photo by amirali mirhashemian on Unsplash

Introduction

As a JavaScript developer, you probably have read or heard that JavaScript is a single-threaded language. Also, I’m pretty sure a lot of JavaScript developers just “believe” and never question the term or concept and have written thousands of lines of asynchronous (multithreaded-ish) code without even understanding how it works (don’t feel ashamed😅, you are not alone).

What is a thread?

According to Wikipedia, a thread in computer science is short for a thread of execution. Threads are a way for a program to divide (termed “split”) itself into two or more simultaneously (or pseudo-simultaneously) running tasks.

From the definition above, we’re simply saying JavaScript can run only one task at a time right? Well, let’s dig in a little deeper.

To understand how JavaScript handles tasks, we need to understand the JavaScript call stack.

The JavaScript call stack is a literal stack data type and it stacks each successive function call on the other and pops off the function when its execution has completed. Below is a visual representation:

Press enter or click to view image in full size
JavaScript call stack demo. Source file

Observe the menu on the right-hand side and focus on the “Call Stack” menu item. Notice how each function call sits on top of the other and gets popped off after its execution completes. But foo was the first function call, right? Why then do we have (anonymous) below foo? This is the main function that runs when we invoke the script, and when this function runs, it encounters three function declarations and one function call (foo) in the global scope. This immediately adds foo to the top of the stack. Now we’re in the block scope of foo and we encounter another function call (console.log()).

Just in case you’re wondering why console.log() didn’t show up on the call stack, the JavaScript engine is pretty fast and I was only able to get this visualized because of the debugger statement. And since I can’t put one in the console.log() function, it pops off immediately it executes.

After the console.log() is popped off, we encounter another function call (bar()) which takes the execution context into the new function and adds the new function on top of the call stack. The foo() function hasn’t left the stack because its execution hasn’t completed so now we have anonymous(), foo() and bar() on the stack. The process is the same for the execution of the bar() function and it puts baz() on top of the call stack. baz() puts console.log() on the stack, pops it off and puts it once again with the farewell message and then pops it off, pops off the baz() function and then returns to bar()’s execution context runs the second console.log() and pops it off the stack, pops bar() off the stack and the same process for foo().

I’m almost certain my words have failed to convey this concept clearly so I took the liberty of creating a gif to help visualize the entire process.

Press enter or click to view image in full size
Visualizing our code’s execution against the call stack

Now you should be able to see how console.log() fits into the process clearly and also how every line of code is executed.

This is how JavaScript runs Synchronous code. All functions run to completion and are popped off the stack when they have nothing else to do.

If we have built a mental model around the way the JavaScript engine executes code using the call stack, we can already begin to question how it can execute multiple tasks simultaneously(or somewhat simultaneously) with just one call stack.

Asynchronous JavaScript

Consider the following snippet of code in contrast to our previous example.

Demonstrating asynchronous JS

If the JavaScript engine was to execute these lines of code just like it handled the previous one we will have the following sequence:

  • The (anonymous) function which is the function that executes the script is called and placed on top of the stack.
  • It starts from the top of the file and discovers 3 function declarations, first, second and main.
  • On line 16, it sees a call to the main() function and adds it to the stack.
  • main() calls first() and first() calls setTimeout(). Going with our mental model, setTimeout() will have to pop off the call stack(complete execution) before main() can call second(). This means that our stack should be blocked for one second right?

Well, this is not the case. setTimeout() strangely disappears from the stack and every other thing continues as though setTimeout() never existed on the stack. And after our code execution completes, the callback function in setTimeout() appears out of nowhere and executes. This is demonstrated in the gif below.

Press enter or click to view image in full size
Visualizing async code execution

Clearly, this is good news for us. We don’t have to wait an entire second for the next line of code to execute. But how is this possible? Where did the setTimeout() call go to?

Well, our mental model shouldn’t change. JavaScript is a single-threaded language that executes code using the call stack, one function call at a time. Environments that run JavaScript(browsers on the client-side and nodejs on the server-side) provide a set of APIs that expose data from the environment and do some very useful tasks with these data. These APIs are not part of the core JavaScript language itself. Instead, they are built on top of the core language and they give you some really useful bells and whistles to enhance your JavaScript code. Think about accessing your filesystem with nodejs, The JavaScript engine doesn’t give you any way to access the file system out of the box. Instead, the Native APIs that nodejs exposes enables us to have access to the filesystem. setTimeout() is also a part of the web APIs and each call to setTimeout() is handled by the browser’s (or nodejs’) APIs.

The event loop

If you know about multithreading you will see that apart from assigning tasks to other threads, you will also be responsible for orchestrating the flow of all the threads to ensure that they do not conflict with each other. However, JavaScript has a beautiful way of handling tasks that abstracts the orchestration from us and predictably executes them.

Whenever we encounter a task that is part of the APIs we talked about previously(setTimeout() for example), it delegates this out to the APIs and when these tasks are completed, the callbacks that were passed to them are queued in the callback queue and the event loop is responsible for dequeuing the callbacks onto the call stack one after the other. This is demonstrated in the gif below.

Press enter or click to view image in full size
Visualizing async code orchestration with the callback queue and web APIs.

Hopefully, this is clear now. If at this point you feel lost, I suggest you take a look at this article.

Get Chukwudi Ngwobia’s stories in your inbox

Join Medium for free to get updates from this writer.

So now, we know how synchronous and asynchronous code is executed but what does that mean for us?

Callback hell

Consider the following snippet:

Async code to log in with a username.

The comments from line 4–6 explains the problem with asynchronous code. Looking at the function, there is only one way to get out the data, we have to pass it as a parameter to another function(a callback function). This is demonstrated below:

Callback function in action.

However, there is a problem with this approach. Imagine we have to log in, get all posts we have and get comments on the posts and then get the users that commented on our posts. It won’t be a pretty sight at all and I will show you:

Callback Hell!

If for some reason, we still need to carry out these instructions with the last user data we got, we will end up nesting callbacks within callbacks and it becomes really difficult to manage.

Promises

According to the MDN Web Docs, A promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

A promise is in one of these states:

  • pending: initial state, neither fulfilled nor rejected.
  • fulfilled: meaning that the operation completed successfully.
  • rejected: meaning that the operation failed.

Promises give us a different (and cleaner) way to deal with asynchronous code.

Promises in action

One interesting thing about promises is the .then() method. Since it returns a promise, it is chainable. So this means we can carry out further operations with promises that resolve.

Now let’s see if we can rescue(refactor) our callback hell-bound file from the previous section.

Our asynchronous calls refactored to use promises

I am trying to prove to you that promises offer a better syntax and then, the “refactored” file has more lines of code 🤦🏿‍♂️. Well, in reality, the process we simulated will be handled in a cleaner way using fetch API which sends a request to an actual API and gives us a promise which resolves with the data from the API or is rejected with the appropriate error message.

Callbacks vs Promises

While we are happy with the improvements that come with promises, wouldn’t it be nice if we could just write our code in the more readable synchronous manner? Consider the following snippet:

The synchronous syntax we all know and love

Imagine we did not have to nest callbacks or even chain promises. This will greatly improve readability but going by the mental model we have of the JavaScript call stack, this means that the event loop will be blocked until login resolves right? So imagine it takes 10seconds to get a user’s data on login, it means that our application will halt for the entire 10secs. By the time we get posts, comments and then the user that created the comment, the time adds up really quickly and we would have frustrated users that will never want to use our app again. But what if I told you that JavaScript gives us some form of syntactic sugar to write asynchronous code synchronously?

Async/Await

JavaScript provides a special syntax that allows us to work with promises in a less complicated way.

There is a caveat that shouldn’t be ignored and that is we can only use this syntax with a special type of function called an async function.

Async functions

An async function.

Async functions are declared using the async keyword as shown above. One interesting thing about async functions is that they always return a promise. We could explicitly return a promise from an async function and this will have the same effect. Notice how in the snippet above, we chain a then() to the func() function call. The return value from func() is automatically passed to console.log() as a parameter.

Await keyword

Remember what we said about regular synchronous JavaScript functions, they always run to completion before being popped off the call stack. But async functions behave quite differently. We can pause the execution of an async function with the await keyword. Consider the following snippet:

A snippet to demonstrate how JavaScript handles the async function

From the output of this code, we can see strange behavior. first() is called, and even though it hasn't completed its execution, the program continues to execute second().

To understand this behavior, let’s take a look at what the await keyword does. When the await keyword is encountered, it makes the interpreter wait until that promise is settled (resolved or rejected). This means that on line 11 of our snippet, the function execution pauses until it gets a value from the getCount() function. Clearly, this mimics the synchronous code style we all know and love so dearly. The difference is, rather than block the call stack, we proceed to handle other tasks (second()) and then return to complete the execution of first() when we’re done with all other pending tasks.

This is just a more elegant way of handling promises when compared to promise.then(). Not only is it pleasing to the eyes to read, but it is also a lot easier to write.

So how can we refactor our codebase to use the async/await syntax? Let’s take a look at one more snippet:

Our promises refactored to use async/await

Notice that we had to wrap all the operations in an async function (asyncOperations()) and all we have to do is call the async function and all our promises will execute one after the other within the function.

It’s really interesting where the JavaScript language is now. Tasks that used to be nightmarish to accomplish have been simplified and the syntax is not as scary as it used to be.

As developers, it is not enough to jump into new features of our tools without understanding the problems they are trying to solve. I’ve seen a lot of codebases where developers litter the await keyword in a lot of places where they aren’t needed. And this can cause performance problems for our applications.

Rule of thumb: If the execution of your script doesn’t depend on the result of an asynchronous operation, do not await it.

In this article, we learned about the JavaScript call stack and how it executes tasks. We also learned that environments in which the JavaScript engine runs (browsers on the client-side and nodejs on the server-side) provide us with APIs we can leverage to write more powerful code. We also learned that callbacks are just nightmarish to deal with and we should use promises instead whenever possible.

One important thing to note is the fact that we did not consider possible error cases in our examples. This is bad practice. Asynchronous processes are not guaranteed to succeed. We should always handle errors gracefully rather than letting them blow up 💣💥 our code.

Thanks for reading!

--

--

Chukwudi Ngwobia
Chukwudi Ngwobia

Written by Chukwudi Ngwobia

Full-time Software Engineer, part-time guitarist, and lifelong learner.