⏳ async/await = Sync-Looking Async Code
Promise chains are better than callbacks. Async/await is even better. Write async code like synchronous. Clean, readable, maintainable.
❌ Promise Chain
getUser(id) .then(user => getOrders(user.id)) .then(orders => getProducts(orders)) .then(products => console.log(products)) .catch(err => console.error(err));
✅ Async/Await
try {
const user = await getUser(id);
const orders = await getOrders(user.id);
const products = await getProducts(orders);
console.log(products);
} catch (err) {
console.error(err);
}
🎯 Advanced Async/Await
// Parallel execution
const [user, orders] = await Promise.all([
getUser(id),
getOrders(userId)
]);
// Error handling
async function fetchData() {
try {
const response = await fetch('/api/data');
if (!response.ok) throw new Error('Network error');
return await response.json();
} catch (error) {
console.error('Fetch failed:', error);
return null;
}
}
// Retry logic
async function fetchWithRetry(url, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await fetch(url);
} catch (err) {
if (i === maxRetries - 1) throw err;
await new Promise(r => setTimeout(r, 1000 * (i + 1)));
}
}
}
// Top-level await (ES2022)
const config = await fetch('/api/config').then(r => r.json());
💡 Benefits
- Readable like synchronous code
- Better error handling (try/catch)
- Easier debugging (stack traces)
- Less nesting than promises
- Works with any promise-based API
“Promise chains were better than callbacks. Async/await is even better. Code looks synchronous, easy to read. My favorite JavaScript feature.”
