Why async/await differs from Promises in Node.js

If both Promises and async/await do the same job, why does the output look different? Both handle asynchronous code in Node.js, but the way they execute makes all the difference. When using a Promise, the code in the main thread doesn’t wait for the background task to finish. It proceeds and executes the next lines while the background task continues. console.log("Start"); // API call (takes 2 seconds) fetch(`https://lnkd.in/dFBr7zPe) // Returns a Promise .then(() => console.log("API call done!")); console.log("End"); Output: Start End API call done! (after 2 seconds) That’s because the main thread doesn’t stop; it just keeps going. Now see the same thing with async/await console.log("Start"); // API call (takes 2 seconds) await fetch(`https://lnkd.in/dFBr7zPe); console.log("API call done!"); console.log("End"); Output: Start API call done! End In the case of await, the main thread pauses execution until it receives the result from the background task. During this wait, that part of the code is temporarily removed from the call stack. Once the result comes back, execution resumes from the same line and continues normally. Here, await tells Node.js to wait for the result before moving ahead. That’s why async/await code is more readable and easier to follow than using .then(). #Nodejs #JavaScript #AsyncProgramming #WebDevelopment #CodingTips

Really well explained! The difference in execution flow between Promises and async/await often confuses beginners, and this example makes it crystal clear.

To view or add a comment, sign in

Explore content categories