When we try to understand asynchrony in javascript we usually go straight to concepts like callbacks, promises, async/await and we leave out something as important as how javascript itself works.
We will therefore start from the innermost part of the program, such as the javascript runtime environment, and from there we will be uncovering layer by layer until we reach the topics mentioned above.
1.Javascript is a single-threaded language.
Javascript code is executed in order, line by line. It must finish executing a piece of code before moving on to the next. This is also known as a synchronous programming model, things happen one at a time.
let a = 1;
let b = 2;
let c = a + b;
console.log(c)
One of the biggest issues with synchronous code comes when you have to call a function that requires a certain amount of time to be solved. The next operation needs to wait even if the result of the previous operation is not required. Think of this situation in big applications, the amount of time required to run a script is very long. Loading times can be slower with synchronous programming.
2.JavaScript code is executed in a single thread, but that doesnβt mean the whole JavaScript runtime environment works in a single thread.
If you take a look at the image above you can see a visual representation of what a javascript runtime environment is. It consists of different elements and features that help to run the javascript code. Those elements are:
Javascript engine: program in charge of executing and running our javascript code, it is basically in charge of translating the code we write to machine language. In fact, there are not one if not several engines: V8 for Chrome, Chakra for Edge, Spidermonkey for Firefox.
The heap: responsible for storing our data. It is used to allocate our variables and objects
The call stack: Used to keep track of multiple function calls. Think of it as a stack of dishes that pile up, and when it comes time to wash them, the best way to do it is to take the dishes from the top until you get to the last one. If it sees an API call it sends it to the Web API container
Web APIs: those are the JavaScript programming APIs you can use to build apps on the Web. Some of the browser apis we have available are the DOM, the Fetch API, the Canvas API, and much more. So any event, API request, setTimeOut, will be placed on here until the event got fired (click a button, scroll) or we received the data from a request (fetching data from a server).
The callback queue: here will be receiving the callbacks from the Web API container. It works in a way that the first callback received is the first one sent to the call stack to be executed.
Event loop: a mechanism that manages the order of execution. It constantly checks the call stack and the callback queue. So when the call stack is empty the event loop immediately passes the callbacks in the queue for its execution.
Here is where the magic happens. The solution to this problem was resolved inside the javascript runtime environment, additional threads are being started to handle different tasks.
3.Asynchronous functions exposed by the Web API extend the language
Now we can see that even though there is the main thread in which all the code we write in our programs is executed (call stack) there are asynchronous functions exposed by the Web API in the browser that perform some operations (fetch data, set local storage, dom manipulation) that do not block the main thread simply because they are not performed in that thread ( waiting on the callback queue).
Important to realize that the concept of more than one thing happening at the same time, or multiple related things happening without waiting for the previous one to be completed is the base of the term Asynchronous.
Therefore, with all of the above, we can conclude that Javascript is asynchronous and not blocking.
Next, we will start to talk about the different mechanisms javascript has brought to the table in order to control and manage these asynchronous actions. Those mechanisms are, as you can guest: callbacks, promises, and async/await functions.
Thanks for reading and if you have any suggestions please don't hesitate to leave a comment, I will be happy to take into account your recommendations.
I'll also leave bellow some links where you can find more info:
https://youtu.be/8aGhZQkoFbQ
https://eloquentjavascript.net/11_async.html
https://medium.com/@gemma.stiles/understanding-the-javascript-runtime-environment-4dd8f52f6fca
Top comments (0)