It just a pain. Why can't it just be synchronous?
We just implement the spec; we don't get to define these APIs. For your question to be answered by the authors, you would have to ask on their project's repo.
But, if you want my guess, I would presume that this kind of async body-reading API allows reading HTTP response status and headers early (because they're always the first thing in a HTTP response), before the full body is even available. Also, it clears the path towards streaming response bodies. So in general, it will allow much more use-cases than if the body-reading API was synchronous.
You can also define your own helper that will make the JSON body available without separately waiting for it:
function fetchJSON(url, options) {
return fetch(url, options).then(function(response) {
return response.json().then(function(data) {
return { status: response.status, headers: response.headers, json: data }
})
})
}
// usage:
fetchJSON(url).then(function(response) {
response.status //=> 200
response.headers //=> Headers
response.json //=> {...}
})
sweet! well thanks for the explanation :+1:
I have gotten around this by using an async wrapper on the then callback, like below in a redux-logic:
``es6
fetch(path).then(async (res) => {
if (res.status !== 201) {
console.error(${path} fetch failed with result, res)
const err = await res.json()
dispatch(actionFailed(err))
throw new Error(Server failed with error: ${JSON.stringify(err)}`)
} else {
return res.json()
}
}).then(data => {
dispatch(actionSucceeded(data))
done()
}).catch(err => {
console.error(err)
done()
})
Most helpful comment
We just implement the spec; we don't get to define these APIs. For your question to be answered by the authors, you would have to ask on their project's repo.
But, if you want my guess, I would presume that this kind of async body-reading API allows reading HTTP response status and headers early (because they're always the first thing in a HTTP response), before the full body is even available. Also, it clears the path towards streaming response bodies. So in general, it will allow much more use-cases than if the body-reading API was synchronous.
You can also define your own helper that will make the JSON body available without separately waiting for it: