Chapter 6 — Asynchronous JavaScript

📚 Chapter Overview

Real-world apps don't like to wait. In this chapter, you will learn how to handle long-running tasks like fetching data from a server without freezing your website, using Callbacks, Promises, and the modern async/await syntax.

Learning Objectives:

6.1 Promises and Callbacks

Part 1 — Definition

A Promise is an object representing the eventual completion (or failure) of an asynchronous operation. It can be in one of three states: Pending, Fulfilled, or Rejected. This is much cleaner than "Callback Hell" (nested functions).

Part 2 — Syntax

const myPromise = new Promise((resolve, reject) => {
    if (success) resolve("Data!");
    else reject("Error");
});

myPromise.then(res => console.log(res));

Part 3 — Example

Problem: Simulate a data delay using setTimeout.

script.js
console.log("Start");
setTimeout(() => {
    console.log("Data loaded after 2 seconds");
}, 2000);
console.log("End");

Observation: "End" prints before the data message because JS is non-blocking.

Part 4 — Video

Video: Coming Soon


6.2 Fetch and Async/Await

Part 1 — Definition

The Fetch API allows you to make network requests to get data from external servers. async/await is special syntax that makes asynchronous code look and behave like synchronous code, making it much easier to read and maintain.

Part 2 — Syntax

async function getData() {
    let response = await fetch(url);
    let data = await response.json();
    return data;
}

Part 3 — Example

Problem: Fetch a random user's information from a public API.

script.js
async function loadUser() {
    const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
    const user = await response.json();
    console.log(`User: ${user.name} from ${user.company.name}`);
}
loadUser();

Part 4 — Video

Video: Coming Soon


🏆 Chapter Challenge

Challenge Objective

Build a "Random Quote Generator".

Requirements

Step-by-Step Process

  1. Create the HTML structure with a blockquote.
  2. Write an async function using fetch.
  3. Update the DOM inside the function.
  4. Link the button to the function using onclick or addEventListener.

Expected Deliverables

Solve in Editor