πŸš€ JavaScript Async/Await vs `.then()` : The Microtask & Event Loop Secret

Ever seen this and wondered why the output changes just by reordering lines? async function hi() { return "there"; } // Version A const waitedhi = await hi(); console.log(waitedhi); hi().then(res =...

By · · 1 min read
πŸš€ JavaScript Async/Await vs `.then()` : The Microtask & Event Loop Secret

Source: DEV Community

Ever seen this and wondered why the output changes just by reordering lines? async function hi() { return "there"; } // Version A const waitedhi = await hi(); console.log(waitedhi); hi().then(res => console.log(res)); console.log("end"); vs // Version B hi().then(res => console.log(res)); const waitedhi = await hi(); console.log(waitedhi); console.log("end"); πŸ‘€ Same code… different output. Why? 🧠 The Hidden Mechanism: Microtasks Both await and .then() use Promises, and both schedule work in the microtask queue. πŸ‘‰ Key rule: Microtasks run in the order they are added (FIFO) ⚑ What await really does await hi(); is roughly: hi().then(result => { // rest of your code }); So: .then() β†’ schedules a microtask await β†’ schedules a microtask (continuation) πŸ”₯ Why order matters Version A await schedules continuation resumes β†’ logs "there" .then() schedules another microtask "end" logs .then() runs βœ… Output: there end there Version B .then() β†’ microtask A await β†’ microtask B Run A β†’ Run

Similar Topics

#artificial intelligence (31552) #data science (24017) #ai (16747) #machine learning (14680) #news & insights (13064) #the library (10944) #deep learning (7655) #gaming (5907) #web/tech (5030) #business (4341) #politics (3519) #large language models (3406) #robotics (3298) #data visualization (2891) #agentic ai (2885) #data engineering (2565) #deep dives (2512) #art (2436) #technology (2395) #editors pick (2388)

Related Posts

Trending on ShareHub

Latest on ShareHub

Browse Topics

#artificial intelligence (31552) #data science (24017) #ai (16738) #generative ai (15034) #crypto (14987) #machine learning (14680) #bitcoin (14229) #featured (13550) #news & insights (13064) #crypto news (11082)

Around the Network