How JavaScript handles async operations

I ran this JavaScript snippet, and the output completely surprised me 😳. Day 10: How JavaScript actually handles a async operations ⚙️. 🧠 Logic: 🔹 JS execution always starts with synchronous code -> so "start", "First" & "end" log first. 🔹 Inside the loop, setTimeout is added to macrotask queue (it will run later). 🔹 Promise.then() is added to microtask queue (these will run right after sync code), cause of high priority then macrotask queue. 🔹 Inside asyncFn(), when execution hits await it pauses that function exec & waits for promise to get resolve. 🔹 In the mean time, event Loop continue with promise callback in microTask, one it's completed, the promise get resolved in asyncFn() & then it prints ("Second") to console. 🔹 And the last, the setTimeout callback in macroTask queue gets executed. So:  ✅ Promise run first (microTasks). ⏱️ SetTimeout run after (macroTasks). That's why promise 0, promise 1, promise 2, and Second appear before all TimeOut logs. #Javascript #InterviewPrep  #100DaysOfCode #CodingChallenge  #JavaScript #CodingInterview #JSChallenges

  • text

To view or add a comment, sign in

Explore content categories