Async and Await in JavaScript Explained with Real Examples
Quick Answer: async and await help us write asynchronous JavaScript code clearly. An async function always returns a Promise. The await keyword waits for a Promise to settle before continuing that function. JavaScript can handle other work while the awaited operation is pending.
1. Why Do We Need Async and Await?
Imagine a school portal serving 10,000 students. Each student opens an attendance report. The portal must request student details and attendance records.
Should the browser stop responding while those requests are running? No. It should remain available while the server responds.
Asynchronous programming = starting work without blocking the current JavaScript flow.
A Promise = an object representing a result that may arrive later.
Before async and await, developers commonly used Promise chains with .then(). Those chains work, but longer workflows can become harder to read.
The problem: Promise chains without async and await
We will use a school attendance portal throughout this example. The portal needs student details and attendance information.
Example 1: Loading a student report with Promise chains
function getStudent() {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
name: "Priya",
studentId: "ST101"
});
}, 500);
});
}
function getAttendance(studentId) {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
studentId: studentId,
presentDays: 22,
totalDays: 25
});
}, 500);
});
}
getStudent()
.then((student) => {
return getAttendance(student.studentId)
.then((attendance) => {
console.log(student.name);
console.log(attendance.presentDays);
});
})
.catch((error) => {
console.error(error);
});
Expected output
Priya 22
This code works, but each new step adds another Promise callback. A larger workflow can become harder to follow.
What becomes difficult?
- Nested callbacks make the main flow harder to scan.
- Adding more dependent requests can increase nesting.
- Error handling becomes less clear across long chains.
- Reading the workflow requires following several callback levels.
Now imagine the same portal handling thousands of report requests. Clear code becomes important for maintenance.
2. The Solution: Use Async and Await
We can write the same workflow with async and await.
The business flow stays the same. The code reads from top to bottom.
Async function = a function that returns a Promise.
Await = a keyword that waits for a Promise result inside an async function.
Example 2: Loading the same report with async and await
function getStudent() {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
name: "Priya",
studentId: "ST101"
});
}, 500);
});
}
function getAttendance(studentId) {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
studentId: studentId,
presentDays: 22,
totalDays: 25
});
}, 500);
});
}
async function loadStudentReport() {
const student = await getStudent();
const attendance =
await getAttendance(student.studentId);
console.log(student.name);
console.log(attendance.presentDays);
}
loadStudentReport();
Expected output
Priya 22
The code now reads like a normal sequence. Each await handles one Promise result.
Important: Await does not freeze the browser or block the JavaScript thread. It pauses the current async function until the Promise settles. JavaScript can process other available work meanwhile.
3. How Async and Await Work Internally
Let's follow the school report request from start to finish.
First, the browser calls loadStudentReport(). The function starts the student request. It reaches await and suspends that function.
When the Promise settles, the function continues with the student result. It then requests attendance and waits again.
The highlighted stages show how each awaited request completes before the next dependent step continues.
Understand the execution steps
- Call: JavaScript starts the async function.
- Request: The student request returns a Promise.
- Wait: The function pauses at the await expression.
- Resume: The Promise settles and provides its result.
- Continue: The attendance request starts with the student ID.
- Finish: The report displays the returned attendance details.
4. Async and Await with Multiple API Requests
Our report needs student details and attendance data. These requests are independent in this example.
We do not need to wait for the first request before starting the second. We can use Promise.all().
Promise.all = a method that waits for every supplied Promise to fulfill. It rejects when one supplied Promise rejects.
Example 3: Run independent requests together
function getStudent() {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
name: "Priya",
studentId: "ST101"
});
}, 500);
});
}
function getAttendanceSummary() {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
presentDays: 22,
totalDays: 25
});
}, 500);
});
}
async function loadReport() {
const [student, attendance] =
await Promise.all([
getStudent(),
getAttendanceSummary()
]);
console.log(student.name);
console.log(
attendance.presentDays + "/" + attendance.totalDays
);
}
loadReport();
Expected output
Priya 22/25
Both requests start before Promise.all waits for their results. This avoids unnecessary sequential waiting.
Two independent requests run together, then their results join for the final report.
Remember: Use sequential await when one request needs another result. Use Promise.all when requests are independent. Do not use Promise.all when the second request needs data from the first.
5. Handling Errors with Try and Catch
Network requests can fail. A server can return an error, or a connection can stop.
We can handle rejected Promises with try and catch.
Example 4: Handle a failed attendance request
function getAttendance() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error("Attendance service is unavailable"));
}, 500);
});
}
async function loadAttendance() {
try {
const attendance = await getAttendance();
console.log(attendance.presentDays);
} catch (error) {
console.error("Could not load attendance:", error.message);
}
}
loadAttendance();
Expected output
Could not load attendance: Attendance service is unavailable
The rejected Promise throws at the await expression. The catch block handles that error.
Use finally for cleanup
finally runs after success or failure. It is useful for hiding loading indicators.
Example 5: Always finish the loading state
async function loadStudentPage() {
console.log("Loading report...");
try {
const student = await getStudent();
console.log(student.name);
} catch (error) {
console.error(error.message);
} finally {
console.log("Loading finished");
}
}
loadStudentPage();
Expected output
Loading report... Priya Loading finished
The finally block runs even when the request fails. It is also useful for cleanup after a successful request.
6. Using Async and Await with Fetch API
fetch() sends an HTTP request and returns a Promise. We can await that Promise.
Here is a browser example using a public sample API. Run it in a browser with network access.
Example 6: Fetch a sample user
async function loadUser() {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users/1"
);
if (!response.ok) {
throw new Error("Could not load user");
}
const user = await response.json();
console.log(user.name);
console.log(user.email);
} catch (error) {
console.error("Request failed:", error.message);
}
}
loadUser();
Expected output for the sample response
Leanne Graham Sincere@april.biz
Important: Fetch does not reject automatically for HTTP error statuses such as 404 or 500. Check response.ok before reading the response body.
7. Async and Await: Common Mistakes
Mistake 1: Forgetting await
Without await, the variable receives a Promise instead of its resolved value.
Wrong approach
async function loadStudent() {
const student = getStudent();
console.log(student.name);
}
Correct approach
async function loadStudent() {
const student = await getStudent();
console.log(student.name);
}
Rule: await the Promise when you need its resolved value.
Mistake 2: Using await without an async function
In regular function bodies, await needs an async function. Modern JavaScript also supports top-level await in modules.
Correct approach
async function loadReport() {
const student = await getStudent();
console.log(student.name);
}
loadReport();
Mistake 3: Waiting for independent requests one by one
Sequential awaits can add avoidable waiting time when requests are independent.
Better approach
const [student, attendance] = await Promise.all([
getStudent(),
getAttendanceSummary()
]);
Mistake 4: Ignoring errors
Unhandled rejected Promises can cause failures that are difficult to diagnose.
Better approach
try {
const student = await getStudent();
console.log(student.name);
} catch (error) {
console.error(error.message);
}
Mistake 5: Thinking async makes every operation faster
Async does not make CPU-heavy work faster by itself. It helps with operations that wait, such as network and timer tasks.
For heavy calculations, consider Web Workers. They can move work away from the main browser thread.
8. Async vs Await vs Promise
| Feature | Meaning | Example |
|---|---|---|
| Promise | Represents a result available later. | fetch(url) |
| async | Makes a function return a Promise. | async function load() |
| await | Waits for a Promise inside an async function. | await fetch(url) |
| Promise.all | Waits for multiple Promises together. | Promise.all(tasks) |
9. Real-World Performance and Architecture
Async and await improve code readability. They do not automatically improve server capacity or network speed.
- Sequential operations: Use await when one result is needed by the next request.
- Independent operations: Use Promise.all when every result is needed together.
- Partial results: Use Promise.allSettled when each task needs its own success or failure result.
- Cancellation: Use AbortController when a request should stop after navigation or a timeout.
- CPU-heavy work: Consider Web Workers for expensive browser calculations.
In production, also consider request timeouts, retries, logging and server limits. Avoid unlimited parallel requests to external services.
10. Interview Questions and Answers
Q1. What is async and await in JavaScript?
Strong answer: Async and await help us write Promise-based code clearly. An async function returns a Promise. Await waits for a Promise result inside that function. It does not block the JavaScript thread.
Q2. Does await block the JavaScript main thread?
Strong answer: No. Await suspends the current async function. JavaScript can handle other work while the Promise is pending. The function continues after the Promise settles.
Q3. What does an async function return?
Strong answer: An async function always returns a Promise. A normal returned value becomes a fulfilled Promise. A thrown error becomes a rejected Promise.
Q4. What is the difference between Promise.all and Promise.allSettled?
Strong answer: Promise.all rejects when any supplied Promise rejects. Promise.allSettled waits until every supplied Promise settles. I use allSettled when I need each task's outcome.
Q5. Can we use await without async?
Strong answer: We can use await inside async functions. Modern JavaScript also supports top-level await in modules. It is not available in every script context.
Q6. Does async and await replace Promises?
Strong answer: No. Async and await use Promises internally. They provide a clearer way to work with Promise results.
11. Hands-On Practice
Beginner: Load student details
- Create a function named
getStudent(). - Return a Promise containing a student's name and ID.
- Use async and await to print the student's name.
Intermediate: Build an attendance report
- Create separate functions for student and attendance details.
- Load both independent results using Promise.all.
- Calculate the attendance percentage.
- Handle errors with try and catch.
Advanced: Handle multiple school services
- Request student, attendance and fee details independently.
- Use Promise.allSettled to collect every result.
- Show successful results even when one request fails.
- Add an AbortController to cancel requests when needed.
12. Key Takeaways
- Async functions always return Promises.
- Await waits for a Promise result inside an async function.
- Await does not block the JavaScript main thread.
- Use Promise.all for independent operations that must all succeed.
- Use try and catch to handle rejected Promises.
- Check response.ok when using fetch.
- Async improves code flow, not CPU performance by itself.
Remember: Use async and await to make asynchronous workflows easier to read. Choose sequential or parallel execution based on the actual dependency between tasks.
13. Explore Further
Continue practising with the official JavaScript documentation:
At Upgradix by Shrash Studio, keep learning through practical examples. Share your solutions, discuss different approaches and help other developers grow.
Learn Technology. Build Your Future.
Quality Technology Education. Completely Free.