Why are these fetch methods asynchronous?

帅比萌擦擦* 提交于 2019-12-19 23:17:20

问题


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

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

This makes sense to me - when we initiate a network call, we return a Promise which lets our thread carry on with other business. When the response is available, the code inside the Promise executes.

However, if I'm interested in the payload of the response, I do so via methods of the response, not properties:

  • arrayBuffer()
  • blob()
  • formData()
  • json()
  • text()

These methods return promises, and I'm unclear as to 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 would processing the response's payload return a promise - it's unclear to me why it should be an async operation.


回答1:


Why are these fetch methods asynchronous?

The naïve answer is "because the specification says so"

  • The arrayBuffer() method, when invoked, must return the result of running consume body with ArrayBuffer.
  • The blob() method, when invoked, must return the result of running consume body with Blob.
  • The formData() method, when invoked, must return the result of running consume body with FormData.
  • The json() method, when invoked, must return the result of running consume body with JSON.
  • The text() method, when invoked, must return the result of running consume body with text.

Of course, that doesn't really answer the question because it leaves open the question of "Why does the spec say so?"

And this is where it gets complicated, because I'm certain of the reasoning, but I have no evidence from an official source to prove it. I'm going to attempt to explain the rational to the best of my understanding, but be aware that everything after here should be treated largely as outside opinion.


When you request data from a resource using the fetch API, you have to wait for the resource to finish downloading before you can use it. This should be reasonably obvious. JavaScript uses asynchronous APIs to handle this behavior so that the work involved doesn't block other scripts, and—more importantly—the UI.

When the resource has finished downloading, the data might be enormous. There's nothing that prevents you from requesting a monolithic JSON object that exceeds 50MB.

What do you think would happen if you attempted to parse 50MB of JSON synchronously? It would block other scripts, and—more importantly—the UI.

Other programmers have already solved how to handle large amounts of data in a performant manner: Streams. In JavaScript, streams are implemented using an asynchronous API so that they don't block, and if you read the consume body details, it's clear that streams are being used to parse the data:

Let stream be body's stream if body is non-null, or an empty ReadableStream object otherwise.

Now, it's certainly possible that the spec could have defined two ways of accessing the data: one synchronous API meant for smaller amounts of data, and one asynchronous API for larger amounts of data, but this would lead to confusion and duplication.

Besides Ya Ain't Gonna Need It. Everything that can be expressed using synchronous code can be expressed in asynchronous code. The reverse is not true. Because of this, a single asynchronous API was created that could handle all use cases.




回答2:


Because the content is not transferred until you start reading it. The headers come first.




回答3:


Looking at the implementation here the operation of fetching json is CPU bound because the creation of the response, along with the body is done once the response promise is done. See the implementation of the json function

That being said, I think that is mostly a design concept so you can chain your promise handlers and only use a single error handler that kicks in, no matter in what stage the error happened.

Like this:

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)
  })

The creation of the already resolved promises is implemented with a pretty low overhead. In the end it is not required to use a promise here, but it makes for better looking code that can be written. At least in my opinion.




回答4:


After reading through the implementation of fetch, it seems that promises are used for a few reasons. For starters, json() relies on a FileReader to convert the response blob into text. FileReaders can't be used until the onload callback, so that's where the promise chain starts.

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

From there, additional promises are used to encapsulate particular errors that might occur and propagating them up to the caller. For example, there are errors that can occur if the body has already be read once before, if the blob doesn't convert to text, and if the text doesn't convert to JSON. Promises are convenient here because any of these various errors will simply end up in the catch block of the caller.

So in conclusion, a promised based api is used for reading fetch responses because: 1. They rely on a FileReader which has to initialize itself asynchronously. 2. fetch would like to propagate a wide variety of errors that may occur in reading the body. Promises allow a uniform way to do this.



来源:https://stackoverflow.com/questions/39170556/why-are-these-fetch-methods-asynchronous

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!