ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

AJAX & Fetch API Tutorial• 6 min read

Async / Await with Fetch & Robust Error Handling

Writing synchronous-looking asynchronous code with try...catch blocks

async and await syntax simplifies Promise consumption, allowing asynchronous code to be read and written like standard sequential code.

Structuring Production Async Handlers

Prefix enclosing functions with async.

await pauses execution until the Promise settles, returning the resolved value directly.

Wrap operations inside try...catch...finally blocks to handle network errors and reset loading states.

Production API Client Function
async function fetchStudentMetrics(studentId) {
  let loading = true;
  try {
    const res = await fetch(`/api/students/${studentId}/metrics`);
    if (!res.ok) {
      throw new Error(`Failed to fetch metrics (HTTP ${res.status})`);
    }
    const metrics = await res.json();
    return { success: true, data: metrics };
  } catch (err) {
    return { success: false, error: err.message };
  } finally {
    loading = false;
  }
}
finally block ensures loading spinners are cleared regardless of success or failure.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which block in a `try...catch...finally` statement is guaranteed to execute regardless of whether an error occurred?