Update fetch api to allow json.

The vast majority of the APIs that I have used as a developer are of type json.

This makes the following code snippet very common and repeatable in all my projects:

fetch('https://example.com/foo') // Fetch the resource
 .then(res => res.json()) // Handle response as json
 .then(data => { ... });  // Do something with the data 

My proposal would be extending the fetch object adding a new {json: true} parameter into the requestInit parameter.

fetch('https://example.com/foo', { json: true } )  // Fetch resource as json
 .then(data => { ... });  // Do something with the data

At the end this is just a little syntax sugar but I think it could be useful. Plus, is a 100% retrocomatible change because it's "just" adding a new field into the RequestInit object.

Regards

2 Likes

Fetch is a WHATWG specification, it’s outside TC39’s jurisdiction.

https://github.com/whatwg/fetch

4 Likes

yeah, the double promise is awkward. wish you could just say fetch().json() or fetch().text()
turns:

const fn = async () => {
const res = await fetch()
const data = await res.json()
}

into:

const fn = async () => {
const data = await fetch().json()
}

2 Likes