Async / Await Syntax
Async/Await lets you write asynchronous code that looks and reads just like clean, synchronous code.
What is it?
`async` and `await` are syntactic sugar built on top of JavaScript Promises introduced in ES2017.
Why is it used?
Eliminates callback chaining and lets you use standard `try...catch` blocks for robust error handling.
Detailed Explanation
Rules of Async/Await:
1. The `async` keyword: Placed before a function declaration. It automatically makes the function return a Promise.
2. The `await` keyword: Can only be used inside an `async` function. It pauses execution until the awaited Promise settles, then returns its resolved value.
3. Error Handling: Wrap `await` calls in standard `try { ... } catch (err) { ... }` blocks.
Syntax Structure
Syntax Blueprint
async function loadData() {
try {
const result = await fetchPromise();
console.log(result);
} catch (error) {
console.error(error);
}
}
Code Example
JAVASCRIPT Code
// Loading User Course Progress with Async/Await
async function loadStudentProgress(userId, courseId) {
try {
console.log(`Checking progress for student ${userId}...`);
// Wait for API response
const response = await fetch(`/api/tutorials/progress?user_id=${userId}&course_id=${courseId}`);
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status}`);
}
const data = await response.json();
console.log("Progress loaded:", data.percentage + "% completed");
return data;
} catch (err) {
console.error("Could not load student progress:", err.message);
return null;
}
}
Explanation of the Code
• `async` marks function as asynchronous.
• `await response.json()` cleanly pauses until JSON parsing finishes.
• `try...catch` catches network and HTTP parsing errors gracefully.
Expected Output
Clean async flow without nested `.then()` callbacks, handling errors elegantly.
Real-World Application
Standard across all modern production web applications and backend Node.js APIs.
Common Mistakes to Avoid
• Forgetting `await` in front of a promise (function receives a pending Promise object instead of the resolved data!).
• Using `await` in a regular non-async function (causes syntax error).
Quick Practice Challenge
Write an async function `getUser()` that awaits a fetch call to '/api/auth/current-user' and logs the username.
Key Takeaways
• `async` functions always return a Promise.
• `await` unwraps the Promise value pause-free.
• Always wrap `await` calls in `try...catch` blocks.