Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 11.2 — fetch
JavaScript · Example 2 of 3 ES2018+

getJSON: POST, check ok, handle every outcome

The 422 reply resolved normally; postJSON turned it into an error because res.ok was false. Only the network failure was a rejected promise from fetch itself. Clear the input and press Save to see the error on the page.

fetch(url, options) sends an HTTP request and returns a promise for a Response; it only rejects on network failure, so you must check response.ok yourself, read the body once with json() or text(), and use an AbortController to cancel or time out.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write async function getName() that fetches data:application/json,{"name":"Meera"}, checks ok, and returns the name. Log the result.

02

Write a fetchWithTimeout(url, ms) helper that rejects with a TimeoutError when the request takes longer than ms.

Explain it without notes

01

Why do you have to check response.ok? When does a fetch promise reject?

02

Why are there two awaits in a typical fetch call?

03

How do you send JSON with fetch, and what goes wrong if you skip JSON.stringify?

04

How do you add a timeout and cancellation to fetch, and how do you tell them apart?

getJSON: POST, check ok, handle every outcome ES2018+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

saved { id: 7, name: 'Asha' }
server said no: HTTP 422: name is required
network problem: Failed to fetch