Can I somehow get the fetch response in the first `then`?
It's quite simple: when you dispatch the a fetch()
request, it returns a promise containing the response. That is resolved by the first .then()
. Resolving this first promise actually returns Response
.
Now this is the tricky part: the methods that read the body of the response, be it .json()
, .text()
, .blob()
.... all return promises. This means that you will need to resolve the second promise in order to get the parsed response.
The flow looks like this:
- Make a
fetch()
request, and it returns a Promise of typeResponse
- When you attempt to resolve the content of the Response, it will return a second Promise, whose type depends on the method you use (e.g.
.json()
returns an object,.text()
returns string,.blob()
returns Blob). - Resolve the second Promise, and you get your actual parsed response body
The first promise returned by fetch
can be useful in some cases. If you want to avoid boilerplate, you could simply create your own function:
function fetch_json(url, opts) {
return fetch(url, opts)
.then(resp => resp.json());
}
fetch_json(your_url)
.then(json => console.log(json));
These days I am using the async/await syntax which is the same thing, but looks less like a boilerplate to me.
const response = await fetch(url)
const data = await response.json()
console.log(data)