Cancel with AbortController, time out with AbortSignal.timeout
abort() with no argument rejects with an AbortError; AbortSignal.timeout() rejects with a TimeoutError, so your code can tell "the user cancelled" from "the server was too slow". The messages shown are Chrome's.
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.
Write async function getName() that fetches data:application/json,{"name":"Meera"}, checks ok, and returns the name. Log the result.
Write a fetchWithTimeout(url, ms) helper that rejects with a TimeoutError when the request takes longer than ms.
Explain it without notes
Why do you have to check response.ok? When does a fetch promise reject?
Why are there two awaits in a typical fetch call?
How do you send JSON with fetch, and what goes wrong if you skip JSON.stringify?
How do you add a timeout and cancellation to fetch, and how do you tell them apart?
Preview
Console
Nothing logged yet.Expected console output
real fetch, aborted -> AbortError: signal is aborted without reason
100ms with 400ms timeout -> done after 100ms
900ms with 300ms timeout -> TimeoutError: signal timed out