Async/Await Behavior in JavaScript Explained

This async / await output confuses even experienced developers 🤯 🧩 JavaScript Output-Based Question (Async / Await) ✅ Correct Output 3 1 4 2 🧠 Why this output comes? (Step-by-Step) 1️⃣ Synchronous code runs first • console.log(3) → prints 3 2️⃣ test() is called • console.log(1) runs immediately → prints 1 3️⃣ await Promise.resolve() • Even though the promise is resolved, await pauses the function execution • Remaining code moves to the microtask queue 4️⃣ Back to synchronous code • console.log(4) → prints 4 5️⃣ Microtasks execute • console.log(2) runs last → prints 2 🔑 Key Takeaways (Interview Insight) ✔️ await is always asynchronous ✔️ Code after await runs in the microtask queue ✔️ Even resolved promises don’t run immediately ✔️ Understanding the event loop is critical for async JavaScript async / await looks synchronous, but behaves asynchronously. #JavaScript #AsyncAwait #InterviewQuestions #FrontendDeveloper #MERNStack #ReactJS

  • text

Output: 3 1 4 2 This happens because JavaScript executes all synchronous code first. The async function runs until it hits await, which pauses execution and queues the remaining code as a microtask (even if the promise is already resolved). Control then returns to the main flow, so the next synchronous log runs. Once the call stack is clear, the microtask resumes, producing the final output.

Understanding this is important, but I’d classify this example as more of a mistake (missing await? function shouldn’t be async?) rather than something you might encounter in any codebase.

If you got knowledge about how the Event Loop works it’s easy to guess what’s next and you can take advantage of it From my point of view it’s a Must Have

3142 would be the outcome this is because of mixed of async and sync functions

It's event loop related question

See more comments

To view or add a comment, sign in

Explore content categories