JavaScript. Why a parser trade?

Question:

I'm trying to figure out the promises. There is this code:

fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => response.json())
    .then(json => console.log(json))

And so fetch returns a promise, we tell it what to do when an HTTP response comes from the server, this response, it turns out, has some kind of inherited json method that parses the response into a JS object.

It is stated that the json method returns a promise, therefore this very promise is returned by a callback in the first then . What does then do with this return from the callback if then also returns a promise?

Okay, let's say there is a new promise in the chain returned from response.json , we call the then method further down the chain and asynchronously wait for the HTTP response to be parsed into a JS object. Why does it need to be done asynchronously ?

As far as I understand, the code outside the promise will not continue to be executed, because the instruction stream will be completely occupied with parsing, is it?

And if the answer is so large that it will take tens of seconds to parse, will the 'dynamics' of the rest of the application rise for this time?

And if we imagine that response.json does not wrap the parser in a promise, but immediately parses the response from the server and returns a JS object, is there any difference in the code above from this?

fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => console.log(response.json()))

Answer:

According to the description of fetch , the promise of fetch itself is resolved as soon as the server sends the response headers, but before the response body is received. Reading the response body over the network occurs separately, by calling any method for obtaining a result from request. The response body can be very large and go through the network in parts, then the json parser will parse it as data is received. Those. it also raises network waits. That is why any of the methods for obtaining data from request is also asynchronous.

Scroll to Top