json()
.json()
.json
is an asynchronous method that parses a stringified JSON response body to a plain Javascript object.
Because json()
method is an asynchronous method, if you don't await
the response, it returns an unresolved Promise
object.
fetch('https://example.org/products.json') .then(response => response.json()) // not async yet // returns Promise wrapped data to next .then chain .then(data => { // another fulfilled Promise; callback is executed after fulfillment console.log(data) })
Alternatively:
const response = await fetch('https://example.org/products.json'); const data = await response.json(); // is async
Why is .json()
async?
After initial fetch
call, only the headers have been read.
To parse the body of json
, the body data has to be read from the incoming stream.
- The whole body is read into memory and then it is parsed.
Since reading TCP stream is async, the .json()
operation is also async.
It's not the parsing, but the retrieving of the data that is async.