问题
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