Exercise 1: Fetch JSON (safe)
Problem Statement
Create a function `fetchJson(url)` that returns JSON. Throw Error for non-2xx responses.
Sample Output:
await fetchJson("https://api.example.com/data") => {id: 1, name: "Test"}
await fetchJson("https://api.example.com/404") => throws Error("HTTP 404")Solution
const fetchJson = async (url) => {
const res = await fetch(url);
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json();
};Explanation
Overall Goal:
- URL se JSON data fetch karna.
- Error handling: non-2xx responses handle karna.
Line 1: Async function
const fetchJson = async (url) => {async→ function async hai (Promise return).url→ API endpoint URL.
Line 2: Fetch request
const res = await fetch(url);fetch(url)→ HTTP GET request (default method).await→ response aane tak wait.res→ Response object (status, headers, body).
Line 3: Status check
if (!res.ok) throw new Error('HTTP ' + res.status);res.ok→ boolean: status 200-299 range me hai?!res.ok→ agar status error hai (400, 500, etc.):throw new Error(...)→ error throw karo.'HTTP ' + res.status→ error message (e.g., "HTTP 404").
Line 4: Parse JSON
return res.json();.json()→ response body ko JSON parse karta hai (Promise return).- Result: JavaScript object/array return.
Real world:
- API clients: backend se data fetch.
- Data loading: user profiles, product lists.
- Dashboard: statistics, reports fetch.
Navigation
Previous
No previous exercise
Next
Exercise 2