JavaScript - How Does Asynchronous Code Work?
Last Updated :
29 Nov, 2024
Asynchronous code in JavaScript allows to execute code in the background without blocking the main thread. Asynchronous JavaScript is mainly used for handling tasks like network requests, file operations, and API calls.
To understand how asynchronous code works, it's important to first know the concept and flow of synchronous code.
Synchronous JavaScript
- Synchronous JavaScript allows data to be accessed in a sequential order, ensuring it is available as needed.
- Users access data from different segments of code that are interrelated or dependent on each other.
- The Call Stack operates in a Last-In-First-Out (LIFO) manner, executing tasks by removing functions from the top of the stack.
JavaScript
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();
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 enables non-blocking operations, executing complex task side-by-side without blocking the main execution thread.

- Asynchronous JavaScript allows users to quickly receive data, especially when fetching from APIs.
- Promises and callbacks are used to manage asynchronous data retrieval.
- Key concepts include the Event Loop, Web API, and Message Queue, which are part of the browser's runtime.
- Asynchronous methods and events (like setTimeout) are handled by Web APIs and move to the Message Queue after completion.
- The Event Loop checks if the Call Stack is empty and transfers tasks from the Message Queue for execution.
How Asynchronous Code Works?
Asynchronous JavaScript enables non-blocking execution of tasks like data fetching. It allows them to run in the background continueing the main thread execution.
It is done in 3 step
- Main Thread Execution: Firstly, JavaScript's main thread processes synchronous code line-by-line.
- Microtasks (like promisies): Promises that resolve immediately queue their
.then()
and .catch()
callbacks as microtasks. - Macrotasks: Then the callback from the functions like setTimeout are places in the task queue, to be executed only after the synchronous code and microtasks have finished.
JavaScript
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.....");
OutputProgram Starts......
Program Ends.....
Promise resolved.....
setTimeout execution....
Example: This example shows how JavaScript handles asynchronous tasks, resolving the promise first, then executing the setTimeout after the synchronous code completes.
JavaScript
// Synchronous code
console.log("Main theread: Program Starts......");
// setTimeout with execution delay time of 0 milliseconds
setTimeout(() => {
console.log("Macro Task: setTimeout 1 execution....");
}, 0);
setTimeout(() => {
console.log("setTimeout 2 execution....");
}, 0);
// Asynchronous code containing promise and callbacks
new Promise((resolve, reject) => {
resolve("Microtask: 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.....");
OutputMain theread: Program Starts......
Program Ends.....
Microtask: Promise 1 resolved.....
Promise 2 resolved.....
Macro Task: setTimeout 1 execution....
setTimeout 2 execution....
How to Implement Asynchronous Code in JavaScript?
Here are a few techniques that can help you implement asynchronous functionality in JavaScript:
- Callbacks: Functions passed as arguments to other functions, executed after the completion of an asynchronous operation. They are simple but can lead to "callback hell" if nested too deeply.
- Promises: Objects that represent the eventual completion (or failure) of an asynchronous operation, allowing for cleaner chaining of operations with .then() for success and .catch() for errors.
- Async/Await: Syntactic sugar built on top of promises, allowing you to write asynchronous code that looks synchronous. Use async before a function declaration and await before a promise to pause execution until the promise is resolved.
- Event Loop: Manages the execution of asynchronous code, ensuring that non-blocking tasks are executed efficiently by handling the Call Stack, Message Queue, and Web APIs.
Similar Reads
How asynchronous JavaScript code gets executed in browser ? Functions or operations that are running in parallel with the other functions or operations are called the asynchronous functions or operations in JavaScript. Asynchronous functions use Callback Functions that get executed later. Let us see an example that demonstrates this: JavaScript setTimeout(fu
3 min read
How to create an Asynchronous function in Javascript? JavaScript is a single-threaded and synchronous language. The code is executed in order one at a time. But Javascript may appear to be asynchronous in some situations. Example: HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title
6 min read
Asynchronous JavaScript Asynchronous JavaScript is a programming approach that enables the non-blocking execution of tasks, allowing concurrent operations, improved responsiveness, and efficient handling of time-consuming operations in web applications, JavaScript is a single-threaded and synchronous language. The code is
2 min read
Synchronous and Asynchronous in JavaScript JavaScript is known for its ability to handle both synchronous and asynchronous operations. Understanding how these two things work is important for writing efficient, responsive, and user-friendly applications. In this article, we will see the differences between synchronous and asynchronous JavaSc
4 min read
How JavaScript works and code is executed behind the scene ? JavaScript is an interesting language in the world and its working procedure quite be different from other languages. JavaScript is synchronous(specific order of execution), single-threaded language(it means JavaScript can only execute one command at a time). Everything in JavaScript happens inside
3 min read
How JavaScript Works? JavaScript is a dynamically typed, cross-platform threaded scripting and programming language, used to put functionality and interactivity at the client side as well as to write logic on the server side of a website. It can display content updates, interactive maps, control multimedia, interactive f
13 min read