Fetch in browsers
These programs are page scripts: fetch is the browser's own call, and the lines under each one are what its console prints. The address is a stand-in API, so the runs below answered it with a fixed reply of two users; a command-line run would try the real address and fail without a network.
GET JSON
fetch takes a URL and returns a promise of the response. Await it, then await json for the parsed body. The compiler cannot know the body shape, so declare an interface and pin the parsed value to it:
interface User { id: number; name: string; } async function loadUsers(): Promise<User[]> { const res = await fetch("https://api.example.com/users"); const users = (await res.json()) as User[]; return users; } async function main(): Promise<void> { const users = await loadUsers(); console.log(users.length, users[0].name); } main();
2 Ada
Two awaits in a row: one for the headers, one for the body. The function returns a promise of users, and the caller awaits that too. The run below got an answer with two users, so it prints the count and the first name.
POST forms
POST sends data instead of asking for it. Pass the method and the body in an options object, with headers that name the format. JSON.stringify turns the object into text the server can read:
async function saveUser(name: string): Promise<void> { await fetch("https://api.example.com/users", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }), }); } async function main(): Promise<void> { await saveUser("Ada"); console.log("saved Ada"); } main();
saved Ada
The Content-Type header tells the server that JSON is coming. Without it, many backends refuse to parse the body at all. The run below posts one user and prints the line it writes once the call returns.
Check response.ok
fetch only rejects on network failure. A missing page still resolves, so check the ok flag before touching the body. Throw a plain error with the status code, and the caller handles every failure in one catch:
interface User { id: number; name: string; } async function loadUsers(): Promise<User[]> { const res = await fetch("https://api.example.com/users"); if (!res.ok) { throw new Error("request failed: " + res.status); } return (await res.json()) as User[]; } async function main(): Promise<void> { try { const users = await loadUsers(); console.log(users.length); } catch (err: unknown) { console.log((err as Error).message); } } main();
request failed: 404
ok is true for statuses 200 through 299. Anything else lands in the throw, and res.status tells exactly which one. The run below met a 404 and printed the message of the error.
Abort slow ones
Slow requests should not hang the page. An AbortController hands its signal to fetch and cancels on demand: the timer below aborts after five seconds, and the awaited fetch rejects at once. The snippet assumes a module script, where top-level await is legal:
async function main(): Promise<void> { const ctrl = new AbortController(); const timer = setTimeout(() => ctrl.abort(), 5000); try { await fetch("https://api.example.com/users", { signal: ctrl.signal }); } catch (err: unknown) { console.log((err as Error).name); } finally { clearTimeout(timer); } } main();
AbortError
The timer fires abort unless the fetch finishes first. finally clears the timer either way, so no stray timeouts survive the request. The run below let the timer win and printed the name of the error, AbortError.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does the promise of
fetchresolve with?Answer
A response object with a status, headers and a promise of the body
The response arrives as soon as the status and headers are in, and the body needs a second await.
-
When does
fetchreject?Answer
Only when the request itself fails, as with a lost connection
A 404 is an answer: the promise resolves with it, which is why a program checks
res.okitself. -
What does
res.okmean?Answer
The status is between 200 and 299
okis the boolean for the two hundreds; every other status needs a decision of its own. -
Why pass the
Content-Type: application/jsonheader with a POST?Answer
To tell the server that the body is JSON
A server reads the body according to its declared format, and many refuse a JSON body without the header.
-
What does
ctrl.abort()do to a request that carries the controller signal?Answer
It makes the awaited promise reject with an abort error
The signal links the controller to the request, so the pending fetch rejects and the finally block cleans up.
-
What does this program print?
async function main(): Promise<void> { const res = new Response("{\"n\": 1}", { status: 200 }); const data = (await res.json()) as { n: number }; console.log(res.ok, data.n); } main();Answer
true 1
A 200 answer is ok, and the parsed body carries the field that the assertion names.
-
What does this program print?
const res = new Response("gone", { status: 404 }); console.log(res.ok, res.status);Answer
false 404
The response object holds any status; 404 makes
okfalse but does not throw by itself. -
What does the compiler say about this program?
async function load(): Promise<number> { const res = await fetch("https://api.example.com/users"); return (await res.json()) as string; } console.log(load);Answer
error TS2322: Type 'string' is not assignable to type 'number'.
The function promises a number, and the value pinned to string cannot be returned as one.
-
What does the compiler say about this program?
async function load(): Promise<void> { const res = await fetch("https://api.example.com/users"); const users = res.json() as { id: number }[]; console.log(users.length); } console.log(load);Answer
error TS2352: Conversion of type 'Promise<any>' to type '{ id: number; }[]' may be a mistake
json()gives a promise, and the missing await leaves a promise where the code expects an array. -
What does the body of a response need before the fields inside it are typed?
Answer
A second await for
json(), and an assertion or a check of the shapeThe body arrives as a promise of text or JSON, and the compiler cannot know the server shape, so the program declares it.
Article author: Arthur Isaev