How does asynchronous code work in JavaScript?


In this article, we will be exploring how async code actually works in JavaScript, how it is initialized, and how it is executed and called. But before moving on let’s look at what is synchronous code and how it is different from asynchronous code

  • Synchronous Code − This implies that the user is having the data that is synchronously called and accessed as available in the order. In this user calls the method and only after the method is called it is executed and checked.

  • In Asynchronous code, the trigger is hit by a user or system. It is not necessary who triggers the function but once the function is triggered it will give a response without completing the execution. For e.g.: Downloading a file from the server.

  • An asynchronous function also has a call stack that calls takes the method calls and records them. This will follow a LIFO structure i.e. Last-In-First-Out where every function of tasks is executed by removing anything that is present at top of the stack.

Example 1

In the below example, we are creating an asynchronous code and checking how it works.

  • The main aim of asynchronous data is to provide faster data access to the user and perform its operations in the background.

  • This approach is useful while using APIs (Application Programming Interfaces) that uses resource or tried to collect the response from the API itself.

  • To handle async data, we use promises or callbacks in JavaScript. These promises or callbacks fetch responses or data from the API easily.

  • It also uses the Call Stack to record events and what function to call next. We also have Event Loop, Web API, and messaging queues to facilitate async programming.

  • Any synchronous method or DOM event uses Web APIs to call a function. But in async calls, we publish a message to a queue which will automatically be executed in the background.

  • The task that Event Loop executes is basically determined whether the stack is empty or not. If the stack is not empty than that particular event loop takes data from the queue to the call stack for execution.

# index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Asynchronous Code</title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <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>
</body>
</html>

Output

Updated on: 22-Apr-2022

194 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements