Chaining Fetch API: Sequencing Network Requests
The Fetch API provides a modern, Promise-based interface for making network requests in the browser. When you need to perform a series of related requests where one depends on the result of a previous one, chaining your fetch() calls is the way to go.
1. Introduction to Fetch API Basics
The fetch() function takes a URL (and optional settings) and returns a Promise that resolves to a Response object. To extract data from that Response, you call another Promise-returning method like .json(), .text(), or .blob().
2. Chaining Fetch Requests
To sequence calls—fetch a user, then their posts, then comments on the first post—you simply return the next fetch() from within a .then(). The next .then() waits for that returned Promise.
3. Error Handling in Fetch Chains
Because fetch() only rejects on network errors, you must check response.ok manually for HTTP errors. A single .catch() at the end will handle any thrown errors.
Exercise: Chaining and Error Handling with Posts
Instructions:
- Fetch all posts (
/posts). - Take the first post’s
id. - Fetch comments for that post (
/posts/{id}/comments). - Log the comment count.
- After each
fetch, checkresponse.okand throw if false. - Use one
.catch()to handle any error, and a final.finally()to signal completion.

