I read in the MDN manual how to get the text from the server response, but I didn’t quite understand why it was a Promise object, because the answer was already received, why it is impossible to read it right away?

For example, why instead

response.text().then(function(text) { // ... }); 

could not be done:

 var text = response.text(); 
  • one
    I changed your question a bit in an attempt to make it a little more detailed and detailed. If you do not agree with the editing, you can roll it back =) - Dmitriy Simushev
  • @DmitriySimushev great edit! - Yuri

1 answer 1

I do not know how it works inside them, I can assume 2 options:

  1. This is done to unify the interfaces so that there are promises everywhere.

  2. Perhaps when calling fetch only headers are read, not the body itself, only then when calling text() the reading of the request body itself begins. Plus, at the time of the call to text() , it probably just starts reading. That is, if it were synchronous, as you propose response.text() , then it would block the main thread, and so response.text().then(...) will work only when the file is read in its entirety.

Correct, if not right.