Topic 26 of 37
The async & await Keywords
Overview
Introduced in ES8, async/await is syntactic sugar over Promises. It allows you to write asynchronous code that looks and behaves like synchronous code, making it dramatically easier to read and debug. An 'async' function always returns a Promise.
Syntax
'await' unwraps the Promise value. If the Promise rejects, it throws an error that is caught by the catch block.
Modern Fetching
javascript
async function fetchUserData(userId) {
try {
// Execution pauses here until the Promise resolves
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
console.log("User:", data);
} catch (error) {
// Errors are caught with standard try/catch!
console.error("Fetch failed:", error);
}
}
fetchUserData(1);Common Pitfalls
- Using 'await' inside a loop (like a for-loop) will execute promises sequentially (slow!). Use Promise.all() to run them in parallel if they don't depend on each other.
Interview Tips
- Explain that 'await' does NOT block the main thread. It only pauses the execution context of that specific async function, allowing other code to run.
Real-World Example
Using Promise.allSettled with async/await to ensure all requests finish even if some fail.
example
javascript
async function syncData() {
const results = await Promise.allSettled([
uploadImage(img),
updateProfile(data)
]);
const failures = results.filter(r => r.status === 'rejected');
if (failures.length) console.warn("Some tasks failed");
}