Asynchronous programming with JavaScript

J
avaScript is a single-threaded language(single call stack). So how can it be asynchronous? Most of us are having same thoughts, right? In this post, I will explain you how we can write asynchronous code in JavaScript. But before getting into that let us see first what is the difference between synchronous and asynchronous.

Difference between synchronous and asynchronous

Sweet and simple way to explain the difference is when we have two lines of code say L1 and L2 where L2 is not executed until L1 is executed. This is called synchronous programming and vice versa is called asynchronous programming.

Let me explain it with help of example:

L1: console.log('asynchronous programming');

L2: console.log('JavaScript');

The output of the console:

asynchronous programming

JavaScript

As we can see L1 line will always execute first followed by the L2 line of code. This is what we call synchronous programming.

Let us see another example:

L1: setTimeout(function() { console.log("asynchronous programming"); }, 0);

L2: console.log('JavaScript');

The output of the console:

JavaScript

asynchronous programming

Confused! It is because setTimeout is an asynchronous function in JavaScript. This is what we will look in this post and will understand how asynchronous code works.

Let's get started.

Why do we need asynchronous programming?

Let us see what will happen if JavaScript doesn't have an asynchronous approach. Refer the code shown below:

var foo = getasyn('/getFoo');

var bar = getasyn('/getBar');

console.log('JavaScript');

console.log(foo);

console.log(bar);

Now let's forget about asynchronous programming and see how above code behaves if its run in a synchronous way.

Firstly foo will get execute and will block the execution of code further(also it will block browser and user cannot perform any action) till the time response is received, next bar will get execute and will block the execution of code further till the time response is received. And then finally console.log statements will be executed. 

Frustrating!!! The reason why the browser is blocked and we can't do anything is because of the call stack have things on it and by the time call stack is not cleared we can't do anything in the browser.

That is the reason why we need an asynchronous approach in JavaScript.

Before diving in further let me give the brief introduction on a V8 engine as I will be using this term in this post.

V8 Engine

V8 JavaScript Engine is an open source JavaScript engine developed by The Chromium Project for the Google Chrome web browser. V8 translates JavaScript code into more efficient machine code instead of using an interpreter. 

JavaScript can perform asynchronous programming with the help of Web APIs.

The components that are involved to do asynchronous programming in JavaScript are:

  1. Heap
  2. Stack
  3. WebAPIs
  4. Event loop
  5. Callback queue

There are lot of JavaScript features which is having asynchronous behavior like:

  1. setTimeout
  2. callback functions
  3. Fetch API and lot more.

Now let's see this in details and see how asynchronous programming works. I will be demonstrating with help of setTimeout function.

Don't worry if it's not 100% clear, at this point of time just have an idea about. I will be showing it visually later.

Heap

Is it correct to say data in JavaScript is stored in heap? NO. Because JavaScript follows ECMAScript standards and it doesn't have any layout for memory storage. So its V8 (on chrome browser) or some other engine which has the capability to store data.  And yes, in V8 variables are stored in heap.

Stack or call stack

The code that is about to execute will be pushed on the stack and once executed it will be pop from the stack.

And if the function (f1) calls, other function (f2) it will be pushed on top of f1. And once f2 is executed it will be pop out followed by f1 when execution is completed.

OK! you might have heard of stack overflow and wondering what it is. Let me show you with the help of an example:

function asyncProgram() {

         asyncProgram();

}

asyncProgram();

stack overflow in JavaScript

It's very clear from the diagram, as asyncProgram() function calls itself and one point comes where there is no capacity in the stack and stack overflow happens.

WebAPIs

As we know JavaScript can do only one task at a time and all the code is pushed to the stack and pops out when executed.

WebAPIs help us to achieve asynchronous behavior. 

As soon as stack see some asynchronous call on the stack it sends that to WebAPIs and carries on with executing remaining code, once the WebAPI has resolved the async call it somehow magically return response from an async call to stack and it gets executed.

Callback queue

Once WebAPI has resolved the response, it sends it to callback queue, the reason is being that it cannot just simply send it to call stack because it will interrupt the execution of the running code.

Event loop

The magic that I was talking in the point above (WebAPIs) is Event loop. Its responsibility is just to monitor callback queue and call stack. As soon as it sees that call stack is empty and has something in callback queue, it will queue request from callback queue to call stack in queue fashion (First come first serve).

Also some of us have question why setTimeout(function() {}, 0); doesn't executes immediately. Reason being clear now because call stack will push it to WebAPI and WebAPI to callback queue. Now callback queue will wait till the time stack is not empty. And stack will get empty after executing all the code.

To understand it visually there is a visual representation of how stack, event loop, callback, and queue interacts with each other. Please follow the link: http://latentflip.com/loupe it will demonstrate what happens behind the scene to achieve asynchronous programming.

In upcoming blogs, I will be sharing more about JavaScript so don't forget to subscribe for latest updates. 

Author Info

Tavish Aggarwal

Website: http://tavishaggarwal.com

Tavish Aggarwal is a front-end Developer working in a Hyderabad. He is very passionate about technology and loves to work in a team.