gpt4 book ai didi

javascript - 为什么这些获取方法是异步的?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:27:43 25 4
gpt4 key购买 nike

Fetch 是用于发出网络请求的新的基于 Promise 的 API:

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

这对我来说很有意义 - 当我们发起网络调用时,我们返回一个 Promise,让我们的线程继续处理其他业务。当响应可用时,Promise 中的代码就会执行。

但是,如果我对响应的有效负载感兴趣,我会通过响应的方法而不是属性来实现:

  • arrayBuffer()
  • blob()
  • 表单数据()
  • json()
  • 文本()

这些方法返回 promise ,我不清楚为什么。

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

为什么处理响应的有效负载会返回一个 promise - 我不清楚为什么它应该是一个异步操作。

最佳答案

Why are these fetch methods asynchronous?

天真的答案是 "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.

当然,这并没有真正回答问题,因为它留下了“规范为什么这么说?”的问题。

这就是事情变得复杂的地方,因为我确定推理,但我没有来自官方来源的证据来证明这一点。我将尝试尽我所能解释理性,但请注意,此处之后的所有内容都应主要视为外部意见。


当您使用获取 API 从资源请求数据时,您必须等待资源完成下载才能使用它。这应该是相当明显的。 JavaScript 使用异步 API 来处理此行为,因此所涉及的工作不会阻塞其他脚本,更重要的是,不会阻塞 UI。

资源下载完成后,数据量可能会很大。没有什么可以阻止您请求超过 50MB 的整体 JSON 对象。

如果您尝试同步解析 50MB 的 JSON,您认为会发生什么?它会阻止其他脚本,更重要的是会阻止 UI。

其他程序员已经解决了如何以高性能方式处理大量数据的问题:Streams。在 JavaScript 中,流是使用异步 API 实现的,因此它们不会阻塞,如果您阅读 consume body细节,很明显流被用来解析数据:

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

现在,该规范当然有可能定义两种访问数据的方式:一种用于较小数据量的同步 API,一种用于较大量数据的异步 API,但这会导致混淆和重复。

此外Ya Ain't Gonna Need It .任何可以用同步代码表达的东西都可以用异步代码表达。反之则不然。因此,创建了一个可以处理所有用例的异步 API。

关于javascript - 为什么这些获取方法是异步的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39170556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com