Fetch诞生记

Fetch作用?

https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch

Fetch API  提供了一个 JavaScript接口,用于访问和操纵HTTP管道的部分,例如请求和响应。它还提供了一个全局 fetch()方法,该方法提供了一种简单,合乎逻辑的方式来跨网络异步获取资源。

这种功能以前是使用  XMLHttpRequest实现的。Fetch提供了一个更好的替代方法,可以很容易地被其他技术使用,例如 Service Workers。Fetch还提供了单个逻辑位置来定义其他HTTP相关概念,例如 CORS和HTTP的扩展。

let myImage = document.querySelector('img');

fetch('flowers.jpg')
.then(function(response) {
    return response.blob();
})
.then(function(myBlob) {
    let objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
});

演变过程:

ajax时代:

http://api.jquery.com/jQuery.get/

此处是jquery封装,如果是原始接口, 则更加复杂。 但是让然需要 以回调函数形式处理 资源返回 结果。

$.get( "ajax/test.html", function( data ) {
  $( ".result" ).html( data );
  alert( "Load was performed." );
});

http://api.jquery.com/jQuery.getScript/

请求个脚本后,然后执行脚本加载后的业务代码。 例如加载的某个jquery插件, 然后才能使用此插件。

var url = "https://code.jquery.com/color/jquery.color.js";
$.getScript( url, function() {
  $( "#go" ).click(function() {
    $( ".block" )
      .animate({
        backgroundColor: "rgb(255, 180, 180)"
      }, 1000 )
      .delay( 500 )
      .animate({
        backgroundColor: "olive"
      }, 1000 )
      .delay( 500 )
      .animate({
        backgroundColor: "#00f"
      }, 1000 );
  });
});

其实现原理类似如下文章介绍。

https://friendlybit.com/js/lazy-loading-asyncronous-javascript/

<script src="http://yourdomain.com/script.js"></script>
使用伪ajax方式获取:
(function() {
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.src = 'http://yourdomain.com/script.js';
    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);
})();

Promise+ajax

http://www.cnblogs.com/iamzhanglei/archive/2013/05/05/3060640.html

function xhr(options) {

    var promise = Promise(),

        req = new XMLHttpRequest();

 

    req.open(options.method || 'GET', options.url, true);

 

    // Set request headers if provided.

    Object.keys(options.headers || {}).forEach(function (key) {

        req.setRequestHeader(key, options.headers[key]);

    });

 

    req.onreadystatechange = function (e) {

        if (req.readyState !== 4) {

            return;

        }

 

        if ([200, 304].indexOf(req.status) === -1) {

            promise.reject('Server responded with a status of ' + req.status);

        } else {

            promise.resolve(e.target.result);

        }

    };

 

    req.send(options.data || void 0);

 

    return promise;

}

使用:

xhr({ url: "xxx.php?a=xxx" }).then(function (msg) {

 

})

此方法为Promise 和 xhr的结合体, 消除了xhr的回调函数。 但是还是有效率问题。因为其实上层组合, 如果是 js 平台实现此功能, 则效率会有提升。

Fetch 诞生:

http://www.cnblogs.com/parry/p/using_fetch_in_nodejs.html

在 AJAX 时代,进行请求 API 等网络请求都是通过 XMLHttpRequest 或者封装后的框架进行网络请求。
现在产生的 fetch 框架简直就是为了提供更加强大、高效的网络请求而生,虽然在目前会有一点浏览器兼容的问题,但是当我们进行 Hybrid App 开发的时候,如我之前介绍的 IonicReact Native,都可以使用 fetch 进行完美的网络请求。

https://segmentfault.com/a/1190000003810652

XMLHttpRequest 是一个设计粗糙的 API,不符合关注分离(Separation of Concerns)的原则,配置和调用方式非常混乱,而且基于事件的异步模型写起来也没有现代的 Promise,generator/yield,async/await 友好。

var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';

xhr.onload = function() {
  console.log(xhr.response);
};

xhr.onerror = function() {
  console.log("Oops, error");
};

xhr.send();

使用 fetch后:

fetch(url).then(function(response) {
  return response.json();
}).then(function(data) {
  console.log(data);
}).catch(function(e) {
  console.log("Oops, error");
});

Fetch Polyfill

https://github.com/github/fetch

window.fetch polyfill

The fetch() function is a Promise-based mechanism for programmatically making web requests in the browser. This project is a polyfill that implements a subset of the standard Fetch specification, enough to make fetch a viable replacement for most uses of XMLHttpRequest in traditional web applications.

This project adheres to the Open Code of Conduct. By participating, you are expected to uphold this code.

原文地址:https://www.cnblogs.com/lightsong/p/6540129.html