β‘ Async/Await = Modern Async
Promises are good. Async/Await is better. Write async code like sync code. Cleaner, more readable.
β Promise Chain
fetchUser()
.then(user => fetchOrders(user))
.then(orders => fetchDetails(orders))
.then(details => console.log(details))
.catch(err => console.error(err));
β Async/Await
try {
const user = await fetchUser();
const orders = await fetchOrders(user);
const details = await fetchDetails(orders);
console.log(details);
} catch (err) {
console.error(err);
}
π Async/Await Examples
// Basic async function
async function getUserData(userId) {
const response = await fetch(`/api/users/${userId}`);
const user = await response.json();
return user;
}
// Error handling
async function getUserWithErrorHandling(userId) {
try {
const user = await fetchUser(userId);
const orders = await fetchOrders(user.id);
return { user, orders };
} catch (error) {
console.error('Failed:', error);
throw new Error(`Failed to get user: ${error.message}`);
}
}
// Parallel execution
async function getUserSummary(userId) {
const userPromise = fetchUser(userId);
const ordersPromise = fetchOrders(userId);
const reviewsPromise = fetchReviews(userId);
const [user, orders, reviews] = await Promise.all([
userPromise,
ordersPromise,
reviewsPromise
]);
return { user, orders, reviews };
}
// Retry pattern
async function fetchWithRetry(url, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const response = await fetch(url);
if (response.ok) return response.json();
} catch (error) {
if (i === maxRetries - 1) throw error;
await delay(1000 * (i + 1));
}
}
}
// Timeout pattern
async function fetchWithTimeout(url, timeoutMs = 5000) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetch(url, { signal: controller.signal });
clearTimeout(timeout);
return response.json();
} catch (error) {
clearTimeout(timeout);
throw error;
}
}
π‘ Async/Await Tips
- Always use try-catch
- Use Promise.all for parallel
- Avoid blocking with await
- Use for I/O operations
- Better than promise chains
“Async/Await makes async code readable. Write sync, run async. Essential for modern JavaScript.”
