Why Async Code Doesn't Run in Order in JavaScript

𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗶𝘀 𝘀𝗶𝗻𝗴𝗹𝗲-𝘁𝗵𝗿𝗲𝗮𝗱𝗲𝗱. But your async code doesn't run in the order you think. Most developers get this wrong — including seniors. What does this print? console.log('1') setTimeout(() => console.log('2'), 0) Promise.resolve().then(() => console.log('3')) console.log('4') Take 10 seconds. Write your answer. Then keep reading. ━━━━━━━━━━━━━━━━━━━━━━━ 𝗧𝗵𝗲 𝗮𝗻𝘀𝘄𝗲𝗿: 1 → 4 → 3 → 2 Most people predict: 1 → 4 → 2 → 3 They're wrong. Here's exactly why. ━━━━━━━━━━━━━━━━━━━━━━━ 𝗧𝗵𝗲 𝗲𝘃𝗲𝗻𝘁 𝗹𝗼𝗼𝗽 𝗵𝗮𝘀 𝘁𝘄𝗼 𝗾𝘂𝗲𝘂𝗲𝘀, 𝗻𝗼𝘁 𝗼𝗻𝗲. 𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸 𝗾𝘂𝗲𝘂𝗲 → Promises, queueMicrotask(), MutationObserver 𝗠𝗮𝗰𝗿𝗼𝘁𝗮𝘀𝗸 𝗾𝘂𝗲𝘂𝗲 → setTimeout, setInterval, I/O, UI events The rule nobody tells you: After every task, the engine drains the ENTIRE microtask queue before picking the next macrotask. Not one microtask. ALL of them. ━━━━━━━━━━━━━━━━━━━━━━━ 𝗧𝗵𝗲 𝗲𝘅𝗮𝗰𝘁 𝗲𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻 𝗼𝗿𝗱𝗲𝗿: Step 1 — Run the call stack (synchronous code first)      → prints '1', queues setTimeout, queues Promise, prints '4' Step 2 — Call stack is empty. Check microtask queue.      → Promise.then is there → prints '3'      → Microtask queue now empty. Step 3 — Now pick the next macrotask.      → setTimeout callback → prints '2' setTimeout(fn, 0) does NOT mean "run immediately." It means "run after all microtasks are done." ━━━━━━━━━━━━━━━━━━━━━━━ 𝗧𝗵𝗲 𝗽𝗿𝗮𝗰𝘁𝗶𝗰𝗮𝗹 𝗶𝗺𝗽𝗮𝗰𝘁: This is why React state updates inside Promises resolve before a setTimeout that was queued at the same time. This is why async/await in Node.js doesn't block I/O — I/O callbacks are macrotasks, but .then() chains are microtasks that run between them. And this is the trap: If you keep creating microtasks inside microtasks, you can starve the macrotask queue permanently. setTimeout never fires. UI never updates. ━━━━━━━━━━━━━━━━━━━━━━━ 𝗡𝗼𝘄 𝘁𝗵𝗲 𝗵𝗮𝗿𝗱𝗲𝗿 𝗼𝗻𝗲: console.log('start') setTimeout(() => console.log('timeout'), 0) Promise.resolve()  .then(() => {   console.log('promise 1')   return Promise.resolve()  })  .then(() => console.log('promise 2')) console.log('end') What's the output? Drop your answer below — I'll reply with the explanation. #JavaScript #FrontendDevelopment #ReactJS #NodeJS #SoftwareEngineering #ImmediateJoiner #OpenToWork #FrontendDeveloper #React #ReactDeveloper

  • text

To view or add a comment, sign in

Explore content categories