Open In App

How does asynchronous code work in JavaScript ?

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:



Example: With the help of the following code, let us understand the concept of Synchronous 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.

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:

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.




<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:




<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.... 

Article Tags :