JavaScript async/await explained

🚀 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗮𝘀𝘆𝗻𝗰/𝗮𝘄𝗮𝗶𝘁: 𝘄𝗵𝘆 𝗶𝘁 𝗹𝗼𝗼𝗸𝘀 𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗯𝘂𝘁 𝗶𝘀𝗻’𝘁 JavaScript doesn’t execute async/await synchronously; it only makes asynchronous code easier to read. Example: console.log("A"); async function test() {  console.log("B");  await Promise.resolve("C");  console.log("D"); } test(); console.log("E"); Output:  A B E D What actually happens: 1) Global execution starts "A" is printed 2) test() is called "B" is printed 3) await Promise.resolve("C") • The promise is already resolved, but await still pauses, 𝗮𝘄𝗮𝗶𝘁 𝗻𝗲𝘃𝗲𝗿 𝗰𝗼𝗻𝘁𝗶𝗻𝘂𝗲𝘀 𝗶𝗺𝗺𝗲𝗱𝗶𝗮𝘁𝗲𝗹𝘆 • Suspends test execution and lets the rest of the code run first • The remaining code (console.log("D")) is scheduled as a microtask 4) Global code continues "E" is printed 5) Microtask queue runs async function resumes from where it paused "D" is printed See? Nothing got blocked. That’s JavaScript for you, and async/await just keeps async code readable. Thanks to Akshay Saini 🚀 for explaining this concept in Namaste Javascript, which made async/await click for me! 👏👏 #JavaScript #AsyncAwait #EventLoop #FrontendDevelopment #WebDevelopment

To view or add a comment, sign in

Explore content categories