How Javascript handles Async code
Tags: javascript, webdev, node
Published: 2020-05-08 00:56:55

When I first started learning Javascript, the concept of async code was very hard to grasp for some reason and I had to read a lot and watch a lot of videos explaining how async code works on Javascript. What made things harder, was that Javascript is single-threaded so I couldn't understand how a single threaded language had the ability to run async code. In this article, I will share my knowledge about async code and how Javascript handles it.

Async programming has been around since early stages of computing And it has been heavily used in the past few years and it's currently in almost all websites and applications as it's now considered the default programming paradigm to obtain high performance and low latency. Before explaining how Javascript handles async programming, let me briefly explain why async programming is important and what exactly it is.

### What is async programming?

Async programming refers to code that does not stop the main process of the program (non blocking code). Some parts of the code do not need to stop the main website/application process to execute. For example, Imagine a blog where users can do CRUD operations on blog posts where the blog posts are saved in MYSQL database. Imagine that the blog doesn't use async programming. Here is a possible scenario:

1- User *A* is creating a post
2- Now the program is busy writing the post to the database
3- At the same time, user *B* wants to read another post
4- Since the program is currently writing to the database, user *B* will have to wait for user *A*'s new post to be written in the database before being able to read another blog post.

Now let's see the same scenario if the database operations are async:

1- User *A* is creating a post
2- The database write operation does not stop the main thread but instead, it's scheduled to run some other time in the future and the program can continue running normally.
3- At the same time, user *B* sends a request to read a different post.
4- Since the program is not busy, it can handle user *B*'s request immediately.

Note that async is not the same as concurrent or multi-threading. As we will see Javascript runs async code but it is single-threaded.

### How async code is modeled in Javascript?

Javascript uses Promises, promises are given that name because they promise to finish execution at some point in the future, however, they do not guarantee when they will finish running. In Javascript, async code is mostly I/O and network requests but most async libraries have corresponding sync APIs and normal code can also be written as promises or you can convert other async libraries APIs to be Promises with libraries like bluebird. 

A promise is usually given 2 functions, one called in case of success of the promise and another called if the promise fails. Those functions are called callbacks, however, callbacks have problems like scope changes that made it hard to use (check [Callback Hell](http://callbackhell.com/) for more). That's why *Async/Await* syntax was eventually introduced. You can learn more about promises [Here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function).

An example of async code is the famous `setTimeout` function that takes one callback function and run it after a specified period of time.

### How does Javascript handles async code?

As mentioned above, Javascript is single-thread. This means that the program cannot run the async code on multiple threads which means that it cannot run multiple processes at the same time. If that's the case then how does Javascript handle async code with a single thread?

The thing is that the async API used in Javascript doesn't run in the Javascript runtime but they are actually APIs exposed by the system running the Javascript program (web APIs for frontend developers or C++ for backend developers). So the async code is actually deferred to the system running the Javascript runtime. But How does the runtime know that the async code finished running? Here comes the *Event Loop* and the *Callback Queue*.

When an async function is done execution, the callback function is pushed to the Callback Queue. Once the Javascript runtime stack is empty, the Event Loop gets the function from the Callback Queue and adds it to the runtime stack and thus the function is executed by the Javascript runtime.

This is how Javascript has async code while being single-threaded. I hope this post was useful and I recommend watching [this video](https://www.youtube.com/watch?v=8aGhZQkoFbQ) for live examples as this helped me a lot when I first started. You can also read [This](https://www.tutorialspoint.com/nodejs/nodejs_event_loop.htm) and [This](https://medium.com/javascript-in-plain-english/javascript-event-loop-y-promises-951ba6845899) to learn more about the Event Loop.