Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How does asynchronous code work in JavaScript ?

  • Last Updated : 24 Nov, 2021

In this article, we will learn about asynchronous code working in JavaScript. Let us understand the basic details which are associated with Synchronous JavaScript.

Synchronous JavaScript:

  • Synchronous JavaScript implies that the user is having the data which is synchronously accessed as well as available in order.
  • In this, the user tries to access the data which is available in different segments of the code (like in different functions or methods), which are interrelated to each other or interdependent with each other.
  • The concept of Call Stack comes into the picture, which is a stack that follows LIFO (Last-In-First-Out) structure wherein every function of task is executed by removing anything which is present at the top of the stack itself.

Example: With the help of the following code, let us understand the concept of Synchronous JavaScript.

JavaScript




<script>
    let secondFunction = () => {
        console.log("GeeksforGeeks....");
        console.log("Second Function execution is completed.....");
    }
 
    let firstFunction = () => {
        console.log("First function Execution Starts.....");
        secondFunction();
        console.log("First Function execution ends here.....");
    }
 
    firstFunction();
</script>

Output:

First function Execution Starts.....
GeeksforGeeks....
Second Function execution is completed.....
First Function execution ends here.....

Working of the above Synchronous code is explained with the help of the following pictorial representation of Call Stack.

  • Every element is removed from the top of the stack and when it is removed it gets printed in the browser’s console.
  • This is how synchronous code actually works whenever different functions are called with their respective data execution too.

Now that we have understood the details associated with Synchronous JavaScript let us now understand what is Asynchronous JavaScript and its working upon execution.

Asynchronous JavaScript:

  • Asynchronous JavaScript simply implies the fact that the user will receive the data in a faster manner.
  • This generally took place whenever the user tries to fetch the data from the API (Application Programming Interface) resource or tries to collect the response from the API itself.
  • To handle the asynchronous data, we use promises or callbacks which helps users easily fetch responses or data from the API with ease.
  • After understanding the basics of Call Stack, some more technical concepts exist like Event Loop, Web API, and Message Queue.
  • All these are not associated with the JavaScript engine, they are actually related to Browser’s JavaScript runtime environment.
  • Whenever any synchronous method or DOM events (like setTimeout or promises or callbacks) comes into the existence, it gets executed into the Web API’s and after its timer gets completed it is pushed into the message queue from where the event loop further pushes that message into the Call Stack for its execution.
  • The task which Event Loop executes is basically determining whether or not the stack is empty. If it is empty then that particular event loop takes data from the message queue to Call Stack for execution.

Example 1: Following are some of the examples where we will show the asynchronous nature of the JavaScript code using promises or callbacks or DOM events.

JavaScript




<script>
    console.log("Program Starts......");
 
    setTimeout(() => {
      console.log("setTimeout execution....");
    }, 0);
 
    new Promise((resolve, reject) => {
      resolve("Promise resolved.....");
    })
     .then((res) => console.log(res))
     .catch((error) => console.log(error));
 
    console.log("Program Ends.....");
</script>

Output:

Program Starts......
Program Ends.....
Promise resolved.....
setTimeout execution....

Example 2:

JavaScript




<script>
    console.log("Program Starts......");
    setTimeout(() => {
        console.log("setTimeout 1 execution....");
    }, 0);
    setTimeout(() => {
        console.log("setTimeout 2 execution....");
    }, 0);
    new Promise((resolve, reject) => {
        resolve("Promise 1 resolved.....");
    }).then((res) => console.log(res))
      .catch((error) => console.log(error));
    new Promise((resolve, reject) => {
        resolve("Promise 2 resolved.....");
    }).then((res) => console.log(res))
      .catch((error) => console.log(error));
    console.log("Program Ends.....");
</script>

Output:

Program Starts......
Program Ends.....
Promise 1 resolved.....
Promise 2 resolved.....
setTimeout 1 execution....
setTimeout 2 execution.... 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!