Some operations take time — loading data from a server, reading a file, waiting for a timer. JavaScript is single-threaded, so it can't just stop and wait or the whole page would freeze. Instead it works asynchronously: it starts the slow task, keeps going, and runs your code when the result arrives. This chapter is how modern apps fetch data smoothly.
Why async?
Imagine clicking "Load results" and the entire page locking up for two seconds while data downloads. Async lets the page stay responsive — the network request runs in the background and your callback fires when it's done.
Promises
A Promise is an object representing a value that isn't ready yet. It will eventually either resolve (success) or reject (failure). You react with .then() and .catch():
fetch("/api/students").then(response => response.json()) // when it arrives, parse JSON.then(data => console.log(data)) // then use it.catch(error => console.error(error)); // if anything failed
async / await
Chaining .then() gets hard to read. async/await lets you write asynchronous code that reads top-to-bottom like normal code. Mark a function async, then await any promise inside it:
async function loadStudents() {const response = await fetch("/api/students");const data = await response.json();console.log(data);return data;}loadStudents();
Fetching data
The fetch API makes HTTP requests. A GET is the default; to send data, pass a config object with a method, headers and a JSON body:
// GETconst res = await fetch("/api/programmes");const programmes = await res.json();// POST — submit a form to the serverconst res2 = await fetch("/api/enquiry", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ name: "Aanya", programme: "data" }),});const result = await res2.json();
Handling errors
With async/await, wrap calls in try/catch. Note that fetch only rejects on network failure — a 404 or 500 still "succeeds", so check response.ok yourself:
async function loadStudents() {try {const res = await fetch("/api/students");if (!res.ok) throw new Error(`HTTP ${res.status}`);const data = await res.json();return data;} catch (error) {console.error("Could not load students:", error);return []; // sensible fallback}}
Practice
Use a free public API (for example a placeholder JSON API) and write an async function that fetches a list, checks response.ok, parses the JSON, and renders each item to the page with the DOM techniques from Chapter 4 — all inside a try/catch.
Key takeaways
- 01Async lets slow tasks (network, timers) run without freezing the single-threaded page.
- 02A Promise represents a future value that resolves or rejects; handle it with .then()/.catch().
- 03async/await writes non-blocking code that reads top-to-bottom — the modern default.
- 04fetch() makes HTTP requests; pass method/headers/body to POST JSON.
- 05Wrap awaits in try/catch, and check response.ok — fetch does not reject on 404/500.
