Asynchronous Javascript

Posted By : Shubham Singh Rawat | 14-Dec-2020

Asynchronous Javascript

 

JavaScript is a single-threaded programming language(unlike ruby) which means code runs in a single line of execution. 

 

Everything comes with tradeoffs, as javascript is single-threaded languages where we don’t have to worry about the concurrency issues hence flow of execution is easily traceable. But due to this, we are also not able to perform long operations such as network access without blocking the main thread.

 

When we request some data from an API. The server may take some time to process the request depending upon the situation. During this time, it blocks the main thread which in turn makes the web page unresponsive.

 

That’s where asynchronous JavaScript comes into play. Using asynchronous JavaScript, we can perform long network requests without blocking the main thread.

 

To understand how asynchronous javascript works, let's recall the flow of execution of simple synchronous javascript code.

 

synchronous code

call stack

 

 

As we can understand from the call stack above that how synchronous javascript works where code executed in a top-to-down manner.

 

After getting an overview of the call stack, and how synchronous JavaScript works, let’s get back to the asynchronous JavaScript.

 

Blocking

 

Let’s suppose we are doing a network request in a synchronous way.

 

Doing a network request takes time which depends upon data size, server, network traffic, and other factors.

 

As Javascript is single-threaded so there is no other thread of executing. Hence there is no way but to wait for the network call to complete and after that further execution takes place. 

 

So you see, we have to wait until the networkRequest has finished. This means these operations are blocking the main thread. So this unnecessary wait will create unresponsiveness which is not ideal.

 

Solution

 

The simplest solution is asynchronous callbacks. We use asynchronous callbacks to make our code non-blocking. For example:

 

 

Here in the above code, I have used the setTimeout method to simulate the network request. 

 

To understand how this code is executed we have to understand a few more concepts such as the event loop and the callback queue (also known as message queue).

 

 

The Event Loop

 

The purpose of the event loop is to look into the call stack and determine whether the call stack is empty or not. If it finds the call stack empty, it looks into the message queue to see any pending callback waiting to get executed.

 

Callback Queue/Message Queue

 

It’s the place where all the callbacks reside in a LIFO manner. 

 

Also Read: JavaScript Promises vs RxJS Observables

 

How the above code executed

 

As soon as the above code loads in the browser, the console.log(‘Hello World’) is pushed to the stack and popped off the stack once it’s finished. After that, a call to networkRequest() is found, so it gets pushed to the top of the stack.

 

Next setTimeout() function is called and it is pushed to the top of the stack. The setTimeout() has two arguments: 1) callback and 2) time in milliseconds (ms).

 

The setTimeout() method starts a timer of 2s in the web APIs environment. At this point, the setTimeout() has finished and it’s popped off from the stack. After this, console.log('The End') is pushed to the stack, executed, and removed from the stack after its completion.

 

Meanwhile, the timer runs out, now the callback is pushed to the message queue. However, it is not immediately executed, and the event loop kicks in.

 

Now we have understood how asynchronous javascript works. Actually, javascript has two facilities to do this.

  1. Using Promises
  2. Using async/await

 

Actually async/await is based upon promises and considered syntactical sugar for using promises.

 

Nowadays developers started using async/await and it also makes their lives easy as code using async/await is more clearer and compact than its promises using counterpart.

 

Should I Use Promises or async-await

 

The answer is that we have to use both.

 

Here are the rules about when to use promises and when to use async-await.

  • The async function returns a promise, actually, they ensure that the returned value must be a promise. The converse is also true. Every function that returns a promise is also considered as an async function.
  • Await is used in front of any promise returning the call in the async function. It stops the execution till the promise gets resolved/rejected.
  • If the output of some function depends on the output of some other function then always use await with the former function call.
  • As to make two functions run in parallel, we have to create two different async functions and then run them in parallel. While to run promises in parallel, we have to create an array of promises and then use Promise.all(promisesArray).
  • Instead of creating large async functions with numerous await asyncFunction() in it, it would be better to create smaller async functions.
  • If your code contains blocking code, it is better to make it an async function. By doing this, you are adding an asynchronous mode to that respective code and make it available to other functions to use it asynchronously.

 

We are a 360-degree SaaS app development company that provides end-to-end software development services with a focus on next-gen technologies. Our development team specializes in using JavaScript technologies like Angular, Node, and ReactJS to build scalable, responsive, and feature-rich web applications. We also have a dedicated team of Full Stack developers that are capable of performing both frontend and backend tasks. Our SaaS application development services address your mission-critical project requirements through high-quality web and mobile applications that are easy to scale. 

About Author

Author Image
Shubham Singh Rawat

He is a technical enthusiast who has keen interest in full-stack web development. He has good experience using java(springboot) in back-end and reactjs in front-end.

Request for Proposal

Name is required

Comment is required

Sending message..