JavaScript Promises and the Event Loop Explained

🚨 A small JavaScript Promise detail that many developers misunderstand While studying the JavaScript Event Loop, I realized something interesting about Promises. Many developers assume that creating a Promise automatically pushes it into the Microtask Queue. But that’s not what actually happens. Let’s look at a simple example. const promise = new Promise((resolve, reject) => { console.log("Executor running"); resolve("Done"); }); When this Promise is created, the function inside the constructor (called the executor function) runs immediately and synchronously inside the Call Stack. So at this point, nothing is added to the Microtask Queue. The Microtask Queue only becomes relevant when we consume the Promise using: • .then() • .catch() • .finally() Example: Promise.resolve("Hello") .then((data) => { console.log(data); }); Here, the callback inside .then() is scheduled in the Microtask Queue. This means it will execute after the current Call Stack becomes empty but before any Macrotasks run. Let’s see a small example that shows this behavior clearly. console.log("Start") Promise.resolve().then(() => { console.log("Promise") }) setTimeout(() => { console.log("Timeout") }, 0) console.log("End") Output: Start End Promise Timeout Why does this happen? Because JavaScript processes tasks in the following order: 1️⃣ Call Stack (synchronous code) 2️⃣ Microtask Queue (Promises) 3️⃣ Macrotask Queue (setTimeout, setInterval) Understanding this flow makes asynchronous JavaScript much easier to reason about and debug. To explore this concept better, I’m currently planning to build a small Event Loop Visualizer that will show: • Call Stack • Microtask Queue • Macrotask Queue working together visually. Stay tuned for that 🚀 Sarthak Sharma Devendra Dhote Ritik Rajput Sheryians Coding School Community #JavaScript #AsyncJavaScript #EventLoop #WebDevelopment #FrontendDevelopment#SheryiansCodingSchool

To view or add a comment, sign in

Explore content categories