【问题标题】:Javascript Fetch Time vs XHR Network TimeJavascript 获取时间与 XHR 网络时间
【发布时间】:2020-04-27 08:03:31
【问题描述】:

我在 javascript 中有一个基本代码,可以通过 api 调用获取数据:

var t0 = performance.now();
fetch(
    'http://domain/service',
    { method: 'GET' }
  )
  .then( response => {
      //handle response...
       t1 = performance.now();
       console.log('Call to fetch-start took ' + (t1 - t0) + ' milliseconds.');
    } )
  .catch( error => console.error('error:', error) )
  .then( () => {
       ...
       t1 = performance.now();
       console.log('Call to fetch-end took ' + (t1 - t0) + ' milliseconds.');
    } );

当我调用它时,Chrome 网络时间显示如下:

但控制台显示如下:

Call to fetch-start took 1931.162 milliseconds.
Call to fetch-end took 2846.36500000488 milliseconds.

我不明白浏览器网络时间和获取时间之间的区别。应该是一样的吧?

【问题讨论】:

  • 看起来response.json() 花了很多时间?
  • 旁注:这不是问题,但像许多人一样,您遇到了footgun in the fetch API。你需要检查response.ok

标签: javascript performance api fetch-api


【解决方案1】:

这是因为当fetch 使用 Body 对象解析时,只完成了标头的协商和获取。
数据的获取仍在进行中,这就是我们可以consume this Body as a stream.

最接近实际提取结束的是Body.arrayBuffer(),它不对提取的数据执行任何转换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    • 2020-12-07
    • 2015-09-16
    • 1970-01-01
    • 2015-07-13
    相关资源
    最近更新 更多