Sub topic 1
Your First Request: How fetch() Works
The Fetch API is the browser's built-in way to send HTTP requests from JavaScript. It is also available in Node.js 18 and later, Deno, and Bun. This chapter covers what happens when you call fetch(), what its Promise gives you, and why getting data out of a response takes two steps.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript functions, objects, and template literals
- Promises and
async/await try/catcherror handling- Basic HTTP concepts: methods, status codes, and headers
- The browser developer tools, especially the Console and Network panels
You can run every example in this chapter by pasting it into the browser console. Modern consoles allow await at the top level.
The Shape of a fetch() Call
fetch() takes one required argument, the resource to request. This is usually a URL string. A second, optional argument holds request options, which a later chapter covers. With only a URL, fetch() sends a GET request.
const promise = fetch('https://jsonplaceholder.typicode.com/todos/1');
console.log(promise); // Promise {<pending>}fetch() never returns data directly. It returns a Promise right away, and the request runs in the background. Your code keeps running while the network does its work.
Two Steps: Headers First, Body Second
The Promise from fetch() resolves to a Response object once the server has sent back the status line and headers. At that point the body may still be arriving. Reading the body is a second asynchronous step, so it returns a second Promise.
This design lets you check the status before you download a large body. It also explains why you see two awaits, or two .then() calls, in nearly every fetch example.
Writing It with async/await
The async/await form reads from top to bottom:
async function getTodo(id) {
const response = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`);
const todo = await response.json();
return todo;
}
const todo = await getTodo(1);
console.log(todo.title);The first await waits for the Response. The second waits for the body to download and be parsed as JSON.
Writing It with .then()
Here is the same request as a Promise chain:
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then((response) => response.json())
.then((todo) => console.log(todo.title))
.catch((err) => console.error('Request failed:', err));Returning response.json() from the first callback passes its Promise down the chain, so the next .then() receives the parsed data. Both styles behave the same way. Choose whichever reads better where you use it.
Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Forgetting the first `await` | `response.json` is undefined because `response` is a Promise | `await fetch(...)` before using the result |
| Forgetting the second `await` | You log `Promise {<pending>}` instead of data | `await response.json()` |
| Not returning inside `.then()` | The next `.then()` receives `undefined` | Return `response.json()` from the callback |
| Using the data outside the async flow | The variable is still empty when you read it | Use the data after the `await` or inside `.then()` |
Watching It in the Network Panel
Open the Network panel in developer tools and run one of the examples above. The request shows up with type fetch. Click it to see the request headers the browser sent, the response status and headers, and the response body. When a request misbehaves, check this panel first, because it shows what actually went over the wire.
Exercise
This code logs "Promise {<pending>}" instead of the todo's title. Why, and how do you fix it? async function show() { const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); const todo = response.json(); console.log(todo); }
Show answer
response.json() reads the body asynchronously and returns a Promise, so todo is a pending Promise rather than the parsed object. Add await: const todo = await response.json(); then log todo.title.
Exercise
Why does fetch() resolve to a Response before the body has been read, instead of resolving straight to the data?
Show answer
The status and headers arrive before the body. Resolving early lets your code check the status and headers, and choose how to read the body (JSON, text, binary, or a stream), before the full body has downloaded.