Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is .json() asynchronous? [duplicate]

I've been following a tutorial and came across the following code snippet:

const myAsyncFunction = async () => {
    const usersResponse = await fetch(
        'https://jsonplaceholder.typicode.com/users'
    )
    const userJson = await usersResponse.json();
    const secondUser = userJson[1];
    console.log(secondUser);
    const posts = await fetch (
        'https://jsonplaceholder.typicode.com/posts?userId=' + secondUser.id
    );
    const postsJson = await posts.json();
    console.log(postsJson);
}
myAsyncFunction();

Shouldn't the converting of a response to a JSON object happen instantly, the same way fetching a value from an array e.g. userJson[1] does? Why is it required to await usersResponse.json() and posts.json()?

like image 559
user3545063 Avatar asked Jan 01 '20 19:01

user3545063


People also ask

Why is json asynchronous?

After the initial fetch() call, only the headers have been read. So, to parse the body as JSON, first the body data has to be read from the incoming stream. And, since reading from the TCP stream is asynchronous, the . json() operation ends up asynchronous.

Is json parse asynchronous?

JSON. parse is not asynchronous... it returns its result when it is ready.

Why do we need to await json?

json() is a method on the Response object that lets you extract a JSON object from the response. The method returns a promise, so you have to wait for the JSON: await response.


1 Answers

After the initial fetch() call, only the headers have been read. So, to parse the body as JSON, first the body data has to be read from the incoming stream. And, since reading from the TCP stream is asynchronous, the .json() operation ends up asynchronous.

Note: the actual parsing of the JSON itself is not asynchronous. It's just the retrieving of the data from the incoming stream that is asynchronous.

like image 145
jfriend00 Avatar answered Sep 22 '22 06:09

jfriend00