JavaScript Async/Await

JavaScript Async/Await Mastery: 7 Advanced Patterns for Error Handling, Parallel Execution, and Real-World API Calls

Master JavaScript async/await with advanced patterns including proper error handling, parallel execution with Promise.all, async iteration, and top-level await for modern applications.

Async/await is a modern way to handle asynchronous operations in JavaScript, making your code cleaner and easier to read. But to use it effectively, you need to understand more than just the basics. Let's dive into pro tips and patterns.

1. Error Handling: The Right Way

Always wrap your await calls in try/catch blocks. For multiple awaits, handle errors gracefully.

async function fetchUserData(userId) {
  try {
    const user = await fetch(`/users/${userId}`);
    const posts = await fetch(`/posts?userId=${userId}`);
    return { user, posts };
  } catch (error) {
    console.error('Failed to fetch data:', error);
    return null; // fallback
  }
}

2. Parallel Execution with Promise.all

Don't await sequentially if tasks are independent. Use Promise.all for concurrency.

async function getDashboardData(userId) {
  try {
    const [user, posts, notifications] = await Promise.all([
      fetch(`/users/${userId}`),
      fetch(`/posts?userId=${userId}`),
      fetch(`/notifications/${userId}`)
    ]);
    return { user, posts, notifications };
  } catch (error) {
    console.error('One of the requests failed:', error);
  }
}

3. Top-Level Await (Modules)

In modern JavaScript modules, you can use await outside an async function.

// In a module
const response = await fetch('/api/config');
const config = await response.json();
export default config;

4. Async Iteration with for await...of

Perfect for handling streams or paginated APIs.

async function* fetchPages(urls) {
  for (const url of urls) {
    yield await fetch(url);
  }
}

for await (const page of fetchPages(urlList)) {
  console.log(page);
}

Master these patterns and you'll write cleaner, faster async code every time.

Comments

Popular posts from this blog

How to Center a Div - The 3 Modern Ways (2026)

Call by Value vs Call by Reference in C Programming (With Simple Examples)

Build a Simple Calculator with HTML, CSS & JavaScript