What is Async and Await?
Async and await are modern JavaScript keywords used to handle asynchronous operations in a simpler and more readable way.
They are built on top of Promises and help you write asynchronous code that looks almost like synchronous code.
Async / Await = Cleaner way to work with Promises
Why Async and Await Were Introduced
Before async/await:
- Promises required .then() chaining
- Code became hard to read for complex flows
Async/await solves:
Callback hell
Long promise chains
Poor readability
The async Keyword
The async keyword is used before a function to make it asynchronous.
Important Rules of async
- An async function always returns a Promise
- Even if you return a value, it is wrapped in a Promise
Example
async function greet() { return "Hello JavaScript";}greet().then(message => console.log(message));Output
Hello JavaScriptThe await Keyword
The await keyword is used inside an async function.
It pauses execution until the Promise is resolved.
Important Rules of await
- Can only be used inside an async function
- Makes async code look synchronous
Example
async function fetchData() { let result = await Promise.resolve("Data Loaded"); console.log(result);}
fetchData();Output
Data LoadedAsync & Await with setTimeout
function getData() { return new Promise(resolve => { setTimeout(() => { resolve("Fetched after 2 seconds"); }, 2000); });}
async function showData() { let data = await getData(); console.log(data);}
showData();Output (after 2 seconds)
Fetched after 2 secondsNo .then()
Easy to read
Handling Errors with Try... Catch
Async/await uses try…catch for error handling.
async function loadData() { try { let result = await Promise.reject("Error occurred"); console.log(result); } catch (error) { console.log(error); }}
loadData();Output
Error occurredClean error handling
Similar to synchronous code
Multiple Await Example
async function processData() { let a = await Promise.resolve(10); let b = await Promise.resolve(20); let c = a + b; console.log(c);}
processData();Output
30Common Mistakes with Async/Await
- Using await outside async function
- Forgetting error handling
- Assuming async code runs instantly
When to Use Async and Await
- API calls
- Database operations
- Fetching remote data
- Sequential async operations
- Cleaner promise handling
Two Minute Drill
- Async / await simplifies asynchronous JavaScript
- async functions always return Promises
- await pauses execution until Promise resolves
- try... catch handles errors cleanly Async / await replaces complex .then( ) chains
- Best used for readable async logic
