Imagine you are ordering food at a restaurant. If the chef starts cooking only after taking everyone’s order, it would take forever! Instead, the chef takes one order, starts cooking, then takes another order while the first one is still being prepared.
This is how asynchronous JavaScript works—it allows tasks to run in the background so your code doesn’t get stuck waiting for one task to finish. This is crucial for things like:
✅ Fetching data from a server
✅ Reading files from a database
✅ Running animations smoothly
JavaScript is single-threaded, meaning it can execute only one task at a time. However, thanks to the Event Loop, it can handle multiple tasks efficiently.
🔹 How the Event Loop Works:
JavaScript starts executing the code line by line (Synchronous Execution).
When it encounters an async task (like fetching data), it sends the task to the Web APIs (provided by the browser).
Once the task is completed, it moves to a callback queue.
The Event Loop constantly checks if the main execution thread is free, and if so, it picks tasks from the callback queue and executes them.
A Better Way to Handle Async Code
A Promise is an object that represents the eventual completion (or failure) of an async task.
Pending → Task is still running
Fulfilled → Task completed successfully
Rejected → Task failed
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data fetched!");
}, 2000);
});
console.log("Start");
promise.then((message) => console.log(message));
console.log("End");
JavaScript uses asynchronous programming to handle time-consuming tasks without blocking execution.
Event Loop ensures JavaScript keeps running smoothly.
Callbacks were the first way to handle async tasks, but they led to callback hell.
Promises make async code easier to read and manage
Join Kunal on Peerlist!
Join amazing folks like Kunal and thousands of other people in tech.
Create ProfileJoin with Kunal’s personal invite link.
0
11
0