Dễ JavaScript

JavaScript Async/Await Best Practices

Master async/await in JavaScript with these best practices and common pitfalls to avoid.

17 Th06, 2026 1 phút 16 Lượt xem 4 Khối code
Sơ đồ
flowchart TD A[async function starts] --> B[reach await fetch] B --> C[function suspends, control returns to caller] C --> D[event loop keeps running other tasks] D --> E{Promise settled?} E -->|resolved| F[resume after await with the value] E -->|rejected| G[throw into try/catch] F --> H[continue to next line / next await]

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 tương tá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í.

Đề bài

Fix the code to run API calls in parallel instead of sequentially

Ngôn ngữJAVASCRIPT

Code khởi tạo

javascript
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

Lời giải · javascript
async function loadDashboard() {
    const [user, stats, notifications] = await Promise.all([
        fetchUser(),
        fetchStats(),
        fetchNotifications()
    ]);

    return { user, stats, notifications };
}