← Back to the Build Your Homepage series
EPISODE 08
Promise · async/await · fetch · error handling

Asynchronous JavaScript

Stop blocking the UI. Use Promises, async/await, and fetch to talk to APIs cleanly — with proper error handling and loading states.

PromiseasyncawaitfetchAPI
Duration
About 2.5 hours
Level
📊 Beginner+
Prerequisite
🎯 js-03
OUTCOME
Fetch and render API data with robust error handling

What you'll learn

  • 1Explain microtask queue and why async is non-blocking
  • 2Consume Promises with .then or async/await
  • 3Use try/catch for async error handling
  • 4Run requests in parallel with Promise.all

1. Why Async?

Network calls, timers, and file reads take time. If JavaScript waited synchronously, the page would freeze. Async lets you schedule "do this when it is ready" and continue.

2. Promises

javascript
fetch("https://api.example.com/users")
  .then(res => res.json())
  .then(users => console.log(users))
  .catch(err => console.error(err))
  .finally(() => hideLoader());

3. async/await (Preferred)

javascript
async function loadUsers() {
  try {
    const res = await fetch("https://api.example.com/users");
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const users = await res.json();
    render(users);
  } catch (err) {
    showError(err.message);
  } finally {
    hideLoader();
  }
}
💡

await only works inside async functions. Top-level await is allowed in ES modules.

4. Parallel Requests

javascript
const [users, posts, comments] = await Promise.all([
  fetch("/api/users").then(r => r.json()),
  fetch("/api/posts").then(r => r.json()),
  fetch("/api/comments").then(r => r.json()),
]);
// All three run concurrently, total time = slowest one

Promise.all rejects if any of them fails. Use Promise.allSettled if you want partial success.

5. fetch Options

javascript
const res = await fetch("/api/posts", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ title: "Hello" }),
  signal: AbortSignal.timeout(5000),  // 5s timeout
});
Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub ↗