📖 Notes LESSON 18 OF 32

Fetch API & Async/Await

⏱️ 30 min
⚡ JavaScript

Talking to Servers

fetch() lets JavaScript request data from an API. async/await makes asynchronous code read top-to-bottom instead of nesting callbacks — this is how your frontend will talk to the backend you build in Section 5.

fetch, async/await, try/catch

🌐
fetch()
Returns a Promise that resolves to a Response object.
⏳
async / await
Pauses a function at each await until the Promise resolves — no .then() chains.
🛡️
try / catch
Wraps awaited calls so network errors don't crash the app silently.
⚡
Promise.all()
Runs multiple async requests in parallel instead of one after another.
Fetching Data Safely
JS
async function getUser(id) {
  try {
    const res = await fetch(`/api/users/${id}`);
    if (!res.ok) throw new Error('Request failed');
    const data = await res.json();
    return data;
  } catch (err) {
    console.error(err);
  }
}

// Run multiple requests in parallel
const [users, posts] = await Promise.all([
  fetch('/api/users').then(r => r.json()),
  fetch('/api/posts').then(r => r.json())
]);
💡
Where you'll use this next
Lesson 21 (useState & useEffect) uses this exact fetch pattern inside a React component to load data when it mounts — the async logic doesn't change, only where it lives.
🗒 Cheat Sheet 📝 Worksheet