๐ 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 =...

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