← JS Mastery | Module 6: Async JavaScript Async/Await & Error Handling
Module 6

Async/Await & Error Handling

⏱ 22 min read ● Intermediate 🆓 Free

Async/Await Syntax

Async/await is syntactic sugar over Promises. It makes async code read like synchronous code while remaining non-blocking. The async keyword makes a function return a Promise; await pauses execution until the Promise resolves.

// async function always returns Promise:
async function greet() {
  return "Hello!";  // auto-wrapped in Promise.resolve()
}
greet().then(console.log);  // "Hello!"

// await pauses the function (not the whole program):
async function loadUser(id) {
  const response = await fetch("/api/users/" + id);
  if (!response.ok) throw new Error("Not found");
  const user = await response.json();
  return user;
}

// Compare readability:
// Promise chain:
fetchUser(1).then(user => fetchPosts(user.id)).then(posts => console.log(posts));

// Async/await:
async function display() {
  const user = await fetchUser(1);
  const posts = await fetchPosts(user.id);
  console.log(posts);
}

Error Handling

// try/catch for async errors:
async function safeLoad() {
  try {
    const data = await fetchData();
    return data;
  } catch (error) {
    console.error("Failed:", error.message);
    return null;
  } finally {
    hideSpinner();
  }
}

// Parallel with error handling:
async function loadAll() {
  // WRONG - sequential (slow):
  const user = await fetchUser(1);
  const posts = await fetchPosts(1);
  
  // RIGHT - parallel (fast):
  const [user, posts] = await Promise.all([fetchUser(1), fetchPosts(1)]);
}

// await in loops - be careful!
// BAD (sequential):
for (const id of ids) {
  const user = await fetchUser(id);  // waits for each
}

// GOOD (parallel):
const users = await Promise.all(ids.map(id => fetchUser(id)));

⚡ Key Takeaways

🎯 Practice Exercises

EXERCISE 1

Rewrite a nested callback function as async/await. Add proper error handling with try/catch and a finally clause for cleanup.

EXERCISE 2 — CHALLENGE

Write fetchWithRetry(url, maxRetries) that retries failed requests up to maxRetries times with exponential backoff (1s, 2s, 4s...).

← Promises