Example 1 — Reading text
Use text() for plain bodies.
JavaScript
async function run() {
const res = { async text() { return "hello"; } };
console.log(await res.text());
}
run();How It Works
- text() returns a string promise.
The common pattern is const res = await fetch(url), verify res.ok, then await res.json(). This page uses a mock Response so the example runs offline.
async function getUser() {
const res = {
ok: true,
status: 200,
async json() { return { id: 7, name: "Ada" }; }
};
if (!res.ok) throw new Error("HTTP " + res.status);
return res.json();
}
getUser().then((u) => console.log(u.name));Use text() for plain bodies.
async function run() {
const res = { async text() { return "hello"; } };
console.log(await res.text());
}
run();Second argument options.
const init = { headers: { Accept: "application/json" } };
console.log(init.headers.Accept);CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful