DEV Community

yongchang zhang
yongchang zhang

Posted on

Practical JavaScript Async/Await Patterns for Clean API Calls

Working with asynchronous API calls is one of the most common tasks in modern JavaScript development. While async/await makes asynchronous code look synchronous and readable, it is still easy to fall into traps like unhandled errors, unnecessary sequential waiting, or hanging requests.

Here are four practical async/await patterns you can use right away to keep your API calls clean, fast, and resilient.

1. Always Check response.ok with fetch

A common surprise for beginners using the Fetch API is that fetch() only rejects on network failures—it does not throw an error for HTTP status codes like 404 or 500.

async function fetchUser(userId) {
  const response = await fetch(`https://api.example.com/users/${userId}`);

  if (!response.ok) {
    throw new Error(`HTTP error! Status: ${response.status}`);
  }

  return response.json();
}
Enter fullscreen mode Exit fullscreen mode

Wrapping this check inside a small helper function ensures you never accidentally try to parse an HTML error page as JSON.

2. Run Independent Requests in Parallel with Promise.all

If you need data from multiple independent endpoints, awaiting them one by one wastes time:

// Slower: runs sequentially
const profile = await fetchUser(1);
const posts = await fetchUserPosts(1);
Enter fullscreen mode Exit fullscreen mode

Instead, start both requests at the same time and await them together using Promise.all():

async function loadDashboard(userId) {
  const [profile, posts] = await Promise.all([
    fetchUser(userId),
    fetchUserPosts(userId),
  ]);

  return { profile, posts };
}
Enter fullscreen mode Exit fullscreen mode

If one request fails, Promise.all() rejects immediately. If you want all requests to finish even when some fail, use Promise.allSettled().

3. Handle Partial Failures with Promise.allSettled

When loading widgets or non-critical sections on a page, one failing API shouldn't break everything else:

async function loadWidgets() {
  const results = await Promise.allSettled([
    fetchWeather(),
    fetchNotifications(),
  ]);

  const weather = results[0].status === "fulfilled" ? results[0].value : null;
  const notifications = results[1].status === "fulfilled" ? results[1].value : [];

  return { weather, notifications };
}
Enter fullscreen mode Exit fullscreen mode

This keeps your UI functional and lets you handle missing data gracefully.

4. Add Timeouts with AbortController

Network requests can sometimes hang indefinitely. You can enforce a clean timeout using AbortController:

async function fetchWithTimeout(url, timeoutMs = 5000) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), timeoutMs);

  try {
    const response = await fetch(url, { signal: controller.signal });
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return await response.json();
  } finally {
    clearTimeout(timer);
  }
}
Enter fullscreen mode Exit fullscreen mode

Notice the finally block: it guarantees the timer is cleaned up whether the request succeeds or fails.


Keep Learning

If you'd like to continue building your JavaScript and web development fundamentals with structured, step-by-step guides, check out Howcodex—a free, organized programming tutorial library covering JavaScript, Python, web development, and core computer science topics.

(Disclosure: I operate Howcodex and maintain its tutorial library.)

Top comments (0)