JavaScript Fetch API with async/await: A Practical Guide
The Fetch API is the standard browser API for making HTTP requests. Combined with async and await, it provides a readable way to load data from REST APIs.
Basic GET Request
async function loadProducts() {
const response = await fetch("/api/products");
const products = await response.json();
console.log(products);
}
The first await waits for the HTTP response. The second waits for the response body to be converted from JSON.
Always Check response.ok
A common mistake is assuming that Fetch rejects the promise for every HTTP error. A response with status 404 or 500 is still a completed HTTP request, so application code should check response.ok.
async function loadProducts() {
const response = await fetch("/api/products");
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return await response.json();
}
Handling Errors
try {
const products = await loadProducts();
renderProducts(products);
} catch (error) {
console.error(error);
showError("Unable to load products.");
}
POST Request
const response = await fetch("/api/products", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Keyboard",
price: 1499
})
});
Abort Slow Requests
For search boxes and other interactive pages, an AbortController can cancel an outdated request.
const controller = new AbortController();
fetch("/api/search?q=dotnet", {
signal: controller.signal
});
controller.abort();
Loading States
For a good user experience, set a loading indicator before the request and clear it in a finally block.
async function refresh() {
setLoading(true);
try {
const data = await loadProducts();
renderProducts(data);
} catch (error) {
showError("Request failed.");
} finally {
setLoading(false);
}
}
Common Mistakes
- Forgetting to check
response.ok. - Calling
response.json()more than once. - Ignoring cancellation for rapidly changing searches.
- Displaying raw server errors to users.
- Assuming network errors and HTTP errors behave identically.
Conclusion
Fetch becomes much easier to maintain when it is wrapped in small async functions with explicit HTTP checks and consistent error handling. This pattern works well for dashboards, forms, search pages, and frontend applications.
Ask AlgoLassi and get an answer plus the tutorials worth studying next.
đŦ Comments
Sign in with Google to publish immediately, or comment anonymously and wait for approval.
Comments will appear here when available.