After understanding asynchronous JavaScript, the next important concept is async and await.
They help us write asynchronous code in a simple and readable way.
πΉ What is async?
*async is a keyword used before a function.
*
**It tells JavaScript:
This function will work with asynchronous code and always returns a Promise.**
Example
`async function greet() {
return "Hello World";
}
greet().then(result => console.log(result));`
πΉ What is await?
await is used inside an async function.
It tells JavaScript:
Wait here until the asynchronous task is completed, then continue.
πΉ Simple Example (Code)
`function getData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data received");
}, 2000);
});
}
async function showData() {
console.log("Fetching data...");
const result = await getData();
console.log(result);
}
showData();`
Output
Fetching data...
Data received
Even though it waits, the browser does not freeze.
π Real-Life Example (Very Easy)
π¦ Online Shopping Example
Without await:
- You order a product
- You keep asking βIs it delivered?β
- Code becomes confusing π΅
With async / await:
- You place an order π
- You wait peacefully
- When delivery arrives, you open it π¦ β‘οΈ Clean, readable, and easy to understand
**
π Why Use Async & Await?
**
- Makes asynchronous code look like synchronous
- Easy for freshers
- Avoids messy .then() chains
- Better readability and debugging
**
π Rules to Remember
**
- await only works inside async functions
- async functions return a Promise
- await pauses the function, not the whole program
Top comments (0)