Challenge - Async flow
Build a fetch flow with error handling using async/await and fetch.
Async data flow
In this challenge you will write an async flow that fetches data with fetch. The function starts with the async keyword; you wait for the response and body with await.
Network requests do not always succeed. So the flow is wrapped in a try block; if an error occurs catch handles it. You also need to check response.ok to catch HTTP errors like 404.
These three parts — async, await and try/catch — form a robust data fetching flow.
Catch HTTP errors
A successful HTTP response sets response.ok to true. On a 404 or 500 it becomes false, but fetch still resolves the promise — so catch does not run.
That is why you check if (!response.ok) and throw yourself: throw new Error('Server error'). This throw makes the flow jump to the catch block.
Now both network and HTTP errors are caught in one place.
Exercise Write the loadUser function
Write the async loadUser(url) function. In a try block call await fetch(url); if response.ok is false throw new Error; read the body with await response.text() and return it. In the catch block call console.error(err) and return null.
Show example solution
Open async function loadUser(url). In the try block call await fetch(url), if (!response.ok) throw new Error('Server error'), read const data = await response.text() and return data. In the catch (err) block call console.error(err) and return null.
Example solution:
async function loadUser(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Server error');
}
const data = await response.text();
return data;
} catch (err) {
console.error(err);
return null;
}
}
Test yourself
-
Await the response
async function load() { const response = ____; const data = await response.text(); return data; }Show answer
async function load() { const response = await fetch(url); const data = await response.text(); return data; } -
What happens when response.ok is false?
- fetch rejects the promise and catch runs
- fetch does not run at all
- fetch resolves the promise and catch does not run
- await throws an error
Show answer
fetch resolves the promise and catch does not run — Correct. fetch resolves even on HTTP errors; you need the response.ok check, not catch.