Fetch API: obtain and read a response
Quick answer
fetch(input, init) returns a promise for a Response. The promise can fulfill for an HTTP error; read status and then consume the body asynchronously.
How it works
Use await fetch(url, options) in an async function. Headers may arrive before the body is fully read. response.text() and response.json() return promises. These examples fetch a local data URL; they test the API without contacting any server. Real requests depend on connectivity, permissions and server behavior.
Local examples
Run in a fresh browser document; no external network is needed. The actual ByteMind editor is unverified.
(async () => {const r=await fetch("data:text/plain,hello");console.log(r.status,await r.text());})()Expected console output:
200 helloA local data URL supplies a successful response.
Run in a fresh browser document; no external network is needed. The actual ByteMind editor is unverified.
(async () => {const r=await fetch("data:application/json,%5B2%2C5%5D");const a=await r.json();console.log(a.length,a[1]);})()Expected console output:
2 5The JSON body is decoded into an array.
Common mistakes
Do not call response.json() on the unresolved fetch promise. Check the response and await its body.
Guided practice
Read a data URL containing a short JSON array and report its length.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Fetch API: obtain and read a response — Knowledge Check
Apply the concept and reason about the example output.
What does fetch initially return?
What does await response.text() produce?
Does a data URL test prove an external server is reachable?
What is the expected console output of Fetch API: obtain and read a response example 1?
(async () => {const r=await fetch("data:text/plain,hello");console.log(r.status,await r.text());})()What is the expected console output of Fetch API: obtain and read a response example 2?
(async () => {const r=await fetch("data:application/json,%5B2%2C5%5D");const a=await r.json();console.log(a.length,a[1]);})()