Asynchronous programming allows JavaScript to perform long-running tasks without freezing the application.
Without asynchronous programming:
โข Websites would become unresponsive while waiting for data
โข Users would have to wait for one task to finish before doing anything else
This concept is essential for API calls, timers, file handling, and modern web applications.
1. What is Synchronous Programming?
In synchronous programming, code executes one line at a time.
The next line waits until the current line finishes.
Example:
console.log("Start");
console.log("Middle");
console.log("End");Output:
Start
Middle
End
2. What is Asynchronous Programming?
In asynchronous programming, long-running tasks run in the background, allowing other code to continue executing.
Example:
console.log("Start");
setTimeout(() => {
console.log("Task Completed");
}, 2000);
console.log("End");Output:
Start
End
Task Completed
3. What is the Call Stack?
The Call Stack is a data structure that keeps track of function execution.
Functions are added to the stack when called and removed after execution.
Example:
function first() {
second();
}
function second() {
console.log("Hello");
}
first();Execution Order:
1. first() is pushed onto the stack
2. second() is pushed
3. console.log() executes
4. second() is removed
5. first() is removed
4. What is the Callback Queue?
The Callback Queue stores asynchronous callbacks until the Call Stack is empty.
Example:
setTimeout(() => {
console.log("Executed");
}, 1000);The callback waits in the queue until JavaScript is ready to execute it.
5. What is the Event Loop?
The Event Loop continuously checks:
โข Is the Call Stack empty?
โข If yes, move callbacks from the Callback Queue to the Call Stack
Example:
console.log("Start");
setTimeout(() => {
console.log("Timeout");
}, 0);
console.log("End");Output:
Start
End
Timeout
Even with a delay of 0, the callback executes only after the Call Stack is empty.
6. Callback Functions
A callback is a function passed as an argument to another function.
Example:
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
function completed() {
console.log("Done");
}
greet("Deepak", completed);Output:
Hello Deepak
Done
7. Callback Hell
Nested callbacks make code difficult to read and maintain.
Example:
getUser(function(user) {
getOrders(user, function(orders) {
getPayment(orders, function(payment) {
console.log(payment);
});
});
});Problems:
โข Hard to read
โข Difficult to debug
โข Difficult to maintain
8. What is a Promise?
A Promise represents the eventual completion or failure of an asynchronous operation.
Promise States:
โข Pending
โข Fulfilled
โข Rejected
Example:
const promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Success");
} else {
reject("Failed");
}
});
promise.then(result => {
console.log(result);
}).catch(error => {
console.log(error);
});9. Promise Chaining
Multiple .then() methods can be chained together.
Example: