Why is .json() asynchronous? [duplicate]

末鹿安然 提交于 2021-02-05 05:52:28

问题


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()?


回答1:


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.



来源:https://stackoverflow.com/questions/59555534/why-is-json-asynchronous

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!