JavaScript Async/Await - Xài Cho Đúng Bài
JavaScript đời mới xài async/await để xử lý mấy tác vụ bất đồng bộ. Đây là mấy cái nên nhớ nằm lòng:
1. Lúc nào cũng phải bắt lỗi
async function fetchUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
return data;
} catch (error) {
console.error('Lấy user thất bại:', error);
throw error;
}
}
2. Chạy song song, đừng chạy tuần tự
Đừng await tuần tự khi có thể chạy song song được:
// ❌ Chậm - Chạy tuần tự
const user = await fetchUser();
const posts = await fetchPosts();
const comments = await fetchComments();
// ✅ Nhanh - Chạy song song
const [user, posts, comments] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchComments()
]);
3. Promise.allSettled cho mấy tác vụ độc lập
const results = await Promise.allSettled([
fetchUser(),
fetchPosts(),
fetchComments()
]);
results.forEach(result => {
if (result.status === 'fulfilled') {
console.log('Ngon rồi:', result.value);
} else {
console.log('Lỗi:', result.reason);
}
});
4. Đừng dùng async trong vòng lặp
// ❌ Dở
for (const id of userIds) {
await processUser(id);
}
// ✅ Ngon
await Promise.all(userIds.map(id => processUser(id)));
Rút gọn lại
- Lúc nào cũng dùng try/catch để bắt lỗi
- Dùng Promise.all() cho mấy việc chạy song song được
- Promise.allSettled() dành cho mấy tác vụ độc lập với nhau
- Đừng await bên trong vòng lặp
Async/await làm code bất đồng bộ nhìn giống đồng bộ, nhưng hiểu Promise vẫn là chuyện phải nắm cho chắc!
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í.
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 };
}

