JavaScript Async/Await Best Practices
Modern JavaScript uses async/await for handling asynchronous operations. Here are the best practices:
1. Always Handle Errors
async function fetchUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
return data;
} catch (error) {
console.error('Failed to fetch user:', error);
throw error;
}
}
2. Parallel Execution
Don't await in sequence when you can run in parallel:
// ❌ Slow - Sequential
const user = await fetchUser();
const posts = await fetchPosts();
const comments = await fetchComments();
// ✅ Fast - Parallel
const [user, posts, comments] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchComments()
]);
3. Promise.allSettled for Independent Operations
const results = await Promise.allSettled([
fetchUser(),
fetchPosts(),
fetchComments()
]);
results.forEach(result => {
if (result.status === 'fulfilled') {
console.log('Success:', result.value);
} else {
console.log('Error:', result.reason);
}
});
4. Avoid Async in Loops
// ❌ Bad
for (const id of userIds) {
await processUser(id);
}
// ✅ Good
await Promise.all(userIds.map(id => processUser(id)));
Key Takeaways
- Always use try/catch for error handling
- Use Promise.all() for parallel operations
- Consider Promise.allSettled() for independent tasks
- Avoid awaiting inside loops
Async/await makes asynchronous code look synchronous, but understanding Promises is still crucial!
Thử thách
Luyện tập ngay điều vừa học. Viết lời giải, mở gợi ý nếu bí.
Đề bài
Fix the code to run API calls in parallel instead of sequentially
Code khởi tạo
async function loadDashboard() {
const user = await fetchUser();
const stats = await fetchStats();
const notifications = await fetchNotifications();
return { user, stats, notifications };
}
Lời giải của bạn
async function loadDashboard() {
const [user, stats, notifications] = await Promise.all([
fetchUser(),
fetchStats(),
fetchNotifications()
]);
return { user, stats, notifications };
}

