fetch: talking to an API
GET, check response.ok, parse JSON, POST a body, and abort a slow request.
Lesson 19 of 23 in JavaScript12 min1 exercise
fetch(url) sends an HTTP request and returns a promise for a Response. A response only rejects on network failure — a 404 is a successful fetch with ok: false. Check it yourself.
async function getTodos() {
const response = await fetch("https://api.example.com/todos");
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
const todos = await response.json();
return todos;
}await fetch("https://api.example.com/todos", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "Learn fetch", done: false }),
});json() returns a promise because the body streams in. Await it once. You can also use response.text() or response.status.
const controller = new AbortController();
setTimeout(() => controller.abort(), 3000);
try {
const response = await fetch(url, { signal: controller.signal });
} catch (error) {
if (error.name === "AbortError") console.log("gave up waiting");
}Try it
Filter what the API sends back
main.js
console · output appears here
Exercises
Checked in your browser · hints and solutions included
01
Exercise
List the open todos
Write an async function openTodos() that fetches https://api.example.com/todos and resolves with the titles of the todos where done is false.
Expected: ["Write a loop", "Ship the project"].
exercise.js
console · run your code or check the answer