Sunday, June 2, 2024
90
rated 0 times [  96] [ 6]  / answers: 1 / hits: 8806  / 5 Years ago, wed, january 1, 2020, 12:00:00

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


More From » asynchronous

 Answers
3

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.


[#5195] Friday, December 27, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emilee

Total Points: 365
Total Questions: 113
Total Answers: 109

Location: Monaco
Member since Fri, Sep 24, 2021
3 Years ago
;