Topics Asynchronous Patterns Async/Await & Error Handling
intermediate 16 min read

Async/Await & Error Handling

Modern asynchronous JavaScript with async/await syntax and proper error handling patterns.

Async/Await

// async function always returns a promise\nasync function getUser(id) {\n  const response = await fetch(`/api/users/${id}`);\n  if (!response.ok) throw new Error(`HTTP ${response.status}`);\n  return response.json();\n}\n\n// Clean sequential flow\nasync function loadDashboard(userId) {\n  try {\n    const user = await getUser(userId);\n    const posts = await getPosts(user.id);\n    const notifications = await getNotifications(user.id);\n    \n    return { user, posts, notifications };\n  } catch (err) {\n    console.error('Dashboard load failed:', err);\n    throw err;\n  }\n}

Error Handling Patterns

// Try/catch wrapper\nasync function safeAsync(fn) {\n  try {\n    return [await fn(), null];\n  } catch (err) {\n    return [null, err];\n  }\n}\n\n// Usage\nconst [data, error] = await safeAsync(() => fetchData());\nif (error) {\n  console.error('Failed:', error.message);\n} else {\n  console.log('Data:', data);\n}\n\n// Promise.allSettled - handle all results\nconst results = await Promise.allSettled([\n  fetch('/api/a'),\n  fetch('/api/b'),\n  fetch('/api/c'),\n]);\n\nfor (const result of results) {\n  if (result.status === 'fulfilled') {\n    console.log('Success:', result.value);\n  } else {\n    console.warn('Failed:', result.reason.message);\n  }\n}

Examples

// Practical async/await example
class ApiClient {
  constructor(baseUrl) {
    this.baseUrl = baseUrl;
  }

  async get(endpoint) {
    const url = `${this.baseUrl}${endpoint}`;
    const response = await fetch(url);
    
    if (!response.ok) {
      throw new ApiError(response.status, await response.text());
    }
    
    return response.json();
  }

  async getWithRetry(endpoint, retries = 3) {
    for (let i = 0; i < retries; i++) {
      try {
        return await this.get(endpoint);
      } catch (err) {
        if (i === retries - 1) throw err;
        console.log(`Retry ${i + 1}/${retries}`);
        await delay(1000 * (i + 1)); // Exponential backoff
      }
    }
  }
}

class ApiError extends Error {
  constructor(status, body) {
    super(`API Error ${status}: ${body}`);
    this.status = status;
  }
}

// Usage
const api = new ApiClient('https://api.example.com');
const data = await api.getWithRetry('/users');
console.log('Users:', data);

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.