提取属于ES6标准还是HTML5标准?

时间:2018-07-29 10:13:11

标签: javascript fetch-api

最近我正在从JQuery.ajax切换到Fetch API,我不确定fetch API是属于新的ES6标准还是H5标准?

1 个答案:

答案 0 :(得分:7)

Fetch APIHTML Living Standard组织的WHATWG的一部分。

网络超文本应用技术工作组 (WHATWG)是一个组织,负责维护和开发 HTML API strong>用于Web应用程序。

根据Preface of the Fetch Living Standard

  

从高层次上讲,获取资源是一个相当简单的操作。请求进入,响应出来。但是,该操作的细节非常复杂,过去常常没有仔细写下来,并且每个API都不相同。

     

众多API提供了获取资源的功能,例如HTML的 img script 元素,CSS的 cursor list-style-image (导航器)。 sendBeacon()和 self.importScripts() JavaScript API。提取标准为这些功能提供了统一的体系结构,因此在提取的各个方面(例如重定向和CORS协议)方面,它们都是一致的。

     

提取标准还定义了fetch() JavaScript API,该API以相当低的抽象水平公开了大多数网络功能。

fetch()的主要目标是,与Promises相比,使用XMLHttpRequest可以使用更简单,更简洁的API来简化网络请求。


示例1:

var myImage = document.querySelector('img');
var myRequest = new Request('flowers.jpg');

fetch(myRequest).then(function(response) {
  return response.blob();
}).then(function(response) {
  var objectURL = URL.createObjectURL(response);
  myImage.src = objectURL;
});

来源:MDN


示例2:

fetch('./api/some.json').then(response => {
  if (response.status !== 200) {
    console.log('Looks like there was a problem. Status Code: ' +
    response.status);
        return;
  }
  return response.json(); // Examine the json in the response
}).then(data => 
  console.log(data);
}).catch(err => {
    console.log('Fetch Error :-S', err); // deal with error
});

或使用async / await

async function doWhatever() {
  try {
    let json = await fetch('./api/some.json').then(x => x.json());
    console.log("Got response", json); // do something with it
    return json; // can consume doWhatever from other functions
  } catch (e) {
    // error in request or converting to json or processing
    console.log('Fetch error :S', e); 
  }
}

来源:Google Developers