Async/Await

Use promises and async/await to express asynchronous workflows and handle failures clearly.

Lesson content

🎯 Goal By the end of this lesson, you'll understand: What is async/await ? Why do we use it? How it works Error handling Real-world example What is Async/Await? Async/Await is a modern way to write asynchronous code using Promises. Simple Definition: async/await lets you write asynchronous code that looks like synchronous code. Syntax async function getData () { const result = await somePromise (); console . log( result ); } async → Makes a function return a Promise. await → Waits for a Promise to resolve. Example function getUser () { return Promise . resolve( "Ajay" ); } async function showUser () { const user = await getUser (); console . log( user ); } showUser (); Output Ajay Error Handling Use try...catch . async function getData () { try { const data = await Promise . resolve( "Success" ); console . log( data ); } catch ( err ) { console . log( err ); } } getData (); Real-Life Example 🍕 Order Pizza │ ▼ await Pizza() │ ▼ Pizza Ready │ ▼ Eat Pizza Promise vs Async/Await Promise getUser () . then( user => console . log( user )) . catch( console . error); Async/Await async function showUser () { try { const user = await getUser (); console . log( user ); } catch ( err ) { console . log( err ); } } Key Points ✅ async makes a function return a Promise. ✅ await waits for a Promise to complete. ✅ await can only be used inside an async function (or at the top level of an ES module). ✅ Use try...catch for error handling. ✅ async/await makes asynchronous code easier to read than .then() chains. 🧠 Easy Formula async → Returns a Promise await → Waits for a Promise try...catch → Handles Errors Remember: async = Promise Function await = Wait for Result try...catch = Handle Errors