NelsonLabs
JavaScript Basics/Async & Fetch (APIs)

Async & Fetch (APIs)

JavaScript is single-threaded — it can only do one thing at a time. But waiting for a database query or API response would freeze the whole page. Async programming solves this by letting the engine continue working while waiting for slow operations to complete.

ANALOGY

Ordering food at a restaurant. You order food and the waiter doesn't freeze until your food is ready — they take other orders and check back when your food is done. JavaScript async works the same way. You kick off a slow operation (fetch data, read a file), and instead of blocking, the engine continues running other code. When the slow operation completes, it fires a callback or resolves a promise.

fetch — making HTTP requests
javascript
// fetch returns a Promise
// Promises represent a value that's not available yet

// The .then() approach (older)
fetch("https://api.example.com/courses")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error("Error:", error));

// async/await — cleaner, reads like synchronous code
async function getCourses() {
  try {
    const response = await fetch("https://api.example.com/courses");

    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error("Failed to fetch courses:", error);
  }
}

const courses = await getCourses();
Promises and async patterns
javascript
// Creating a Promise
const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));

async function delayed() {
  console.log("Starting...");
  await wait(2000);  // wait 2 seconds
  console.log("Done after 2 seconds");
}

// Running multiple async operations in parallel
const [users, courses, stats] = await Promise.all([
  fetch("/api/users").then(r => r.json()),
  fetch("/api/courses").then(r => r.json()),
  fetch("/api/stats").then(r => r.json()),
]);
// All three requests fire simultaneously
// Waits for all three to finish before continuing