Why are these sampling methods asynchronous?

Fetch is the new Promise-based API for creating network requests:

fetch('https://www.everythingisawesome.com/')
  .then(response => console.log('status: ', response.status));

It makes sense to me - when we initiate a network call, we return Promise, which allows our thread to continue working with another business. When an answer is available, the code inside Promise is executed.

However, if I am interested in the response payload, I do this using the response methods, not the properties:

  • ArrayBuffer ()
  • blob ()
  • FormData ()
  • JSON ()
  • text()

These methods return promises, and I don't understand why.

fetch('https://www.everythingisawesome.com/') //IO bound
  .then(response => response.json()); //We now have the response, so this operation is CPU bound - isn't it?
  .then(entity => console.log(entity.name));

Why handling the response payload returns a promise - I don’t understand why this should be an async operation.

+4
source share
4 answers

Why are these sampling methods asynchronous?

na & iuml; ve ", "

  • arrayBuffer() ArrayBuffer.
  • blob() Blob.
  • formData() FormData.
  • json(), , JSON.
  • text() .

, , " ?"

, , , . , , , .


API- Fetch, , . . JavaScript API , , , .

, . JSON, 50 .

, , 50 JSON ? , , .

, : . JavaScript API, , , , :

, ReadableStream .

, , , : API, , API , .

. , , . . - API, .

0

, . .

0

, json , , . . json

, , , , , .

:

fetch('https://www.everythingisawesome.com/')
  .then(function(response) {
    return response.json()
  })
  .then(function(json) {
    console.log('parsed json', json)
  })
  .catch(function(ex) {
    console.log('parsing or loading failed', ex)
  })

promises . , , , . , .

0

, promises . -, json() FileReader . FileReaders onload, .

function fileReaderReady(reader) {
  return new Promise(function(resolve, reject) {
    reader.onload = function() {
      resolve(reader.result)
    }
    reader.onerror = function() {
      reject(reader.error)
    }
  })
}

promises , , . , , , , blob , JSON. promises , catch .

, , api , : 1. FileReader, . 2. fetch , . promises .

0

Source: https://habr.com/ru/post/1652627/


All Articles