Kunal Shinde

Mar 12, 2025 • 1 min read

A Simple Guide to Asynchronous JavaScript​: Event Loop, Callbacks, and Promises

Why Do We Need Asynchronous Code?

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

Understanding the Event Loop

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:

  1. JavaScript starts executing the code line by line (Synchronous Execution).

  2. When it encounters an async task (like fetching data), it sends the task to the Web APIs (provided by the browser).

  3. Once the task is completed, it moves to a callback queue.

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

  5. A Better Way to Handle Async Code

A Promise is an object that represents the eventual completion (or failure) of an async task.

Promise States:

  • 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 Profile

Join with Kunal’s personal invite link.

0

11

0