Module 8: Asynchronous JavaScript
Fetch, HTTP, and API Requests
Request JSON from an API and distinguish network errors from HTTP error responses.
The Fetch API provides a promise-based way to make HTTP requests in browser environments and many server-side runtimes. A fulfilled fetch promise does not necessarily mean the server returned a successful status; HTTP responses such as 404 and 500 still resolve to a Response object.
async function getPosts() {
const response = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=5");
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return response.json();
}
getPosts()
.then(posts => console.log(posts))
.catch(error => console.error("Could not load posts", error));
response.json() is asynchronous and returns a promise. The parsed body still needs validation; do not assume the server returned the exact shape your UI expects.
Sending data#
const response = await fetch("/api/items", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "Learn async JavaScript" }),
});
The endpoint and allowed methods depend on your server. Include authentication and authorization rules on the server when required. Do not put secret API keys in frontend code.
Loading and error states#
A robust UI communicates loading, success, empty results, and failure. Prevent duplicate submissions when necessary, and consider cancellation with AbortController when a user navigates away or changes a search.
Practice#
Fetch a small public JSON dataset, check response.ok, parse the result, handle failures, and display a loading message until the request completes.