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:
- Understand the Event Loop and Non-blocking code.
- Master Promises and
.then(). - Use
Fetch APIto get live data from the web.
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.
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.
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
- Fetch a quote from a public API (like
https://api.quotable.io/random). - Display the Quote and the Author on the page dynamically.
- Add a button to fetch a "New Quote" without refreshing the page.
Step-by-Step Process
- Create the HTML structure with a
blockquote. - Write an
asyncfunction usingfetch. - Update the DOM inside the function.
- Link the button to the function using
onclickoraddEventListener.
Expected Deliverables
quote.htmlsource file.