Async and Await in JavaScript (Easy Explanation for Freshers)
Source: Dev.to
Introduction
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 Analogy
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 📦
Result: clean, readable, and easy to understand.
Why Use Async & Await?
- Makes asynchronous code look like synchronous code.
- Easy for freshers to grasp.
- Avoids messy
.then()chains. - Improves readability and debugging.
Rules to Remember
awaitonly works insideasyncfunctions.asyncfunctions always return a Promise.awaitpauses the function, not the whole program.