网络科技

    今日:733| 主题:244858
收藏本版
互联网、科技极客的综合动态。

[其他] Fetch – Modern Async Server Calls

[复制链接]
不见不散 发表于 2016-10-4 23:15:48
128 1

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
Being a web developer right now is exciting and confusing. We keep gettingnew tools, but they all seem to come with more tools of their own .
   It's refreshing when we get a near-total replacement for something that is actually simpler . XMLHttpRequest (XHR) is the definition of an old, confusing, complex tool. Fetch API is the simpler replacement.
  Fetch vs. XHR?

  Fetch is a brand new way of making asynchronous calls to the server. Before we dive into the details, let's look at an example of Fetch versus XHR. To make this simple, we'll just request a file (jQuery in this case) from the Google CDN and just dump it to the console.
  Fetch Example

  You can run the example code below. You may want to open your F12 network tools to compare it to XHR.
  Now, let's take a look at this using XHR.
  XHR Example

  Again, you can try it below.
  This is a pain to write and read. I had to Google what "readyState 4" even meant (request finished and response ready) to write this post. Why do I have to send a null?
  XMLHttpRequest is the definition of an old, confusing, complex tool.
  In reality, a lot of devs just include jQuery and write this:
  [code]$("#basicjQueryButton").on("click", function() {
    // Loading the jQuery code
    $.get("https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js", function(data) {
        console.log(data);
        alert("Done using jQuery!");
    });
});[/code]   We download 34.5KB (as of jQuery 3.1.0), sometimes just for this functionality. You don't need to do this anymore.
  Now There Is Fetch

  The Fetch API gives us a generic Request and Response that we can use to GET/POST/PUT/DELETE/HEAD data to and from the server. It uses promises which makes it easier to code, as well as much easier to read. Because it is promise-based, it even chains nicely into other methods.
   It's useable today in Chrome, Edge and Firefox, and other browsers through a polyfill .
   
Fetch – Modern Async Server Calls-1 (definition,developer,something,actually,request)

  Promises?

   Before diving into the advanced features of Fetch, let's take a brief look at promises. If you want to learn more, I recommend this really excellent post from Jake Archibald .
  Promises are a new way of dealing with asynchronous code in JavaScript that is simpler than chains of callbacks. Promises make it easy to write code that reads like human language. For example, you could write something like this:
  [code]LoadMyData()
    .then(ProcessMyData)
    .then(DoSomethingElse)
    .catch(HandleError);[/code]  There is a lot more to promises, but for this article you should know the following:
   * Promises start off pending
   * Promises resolve as either fulfilled or rejected
   * Fulfilled promises trigger a .then() call
   * Rejected promises trigger a .catch() call
  * All of this happens asynchronously, when the previous promise completes
  Request & Response Object

  The example shown above defaulted to a simple GET and didn't set any advanced headers. However, Fetch allows you advanced control of your Request object before making a request, and lets you query the Response object after.
  For example, say your application wants to do the following:
  
       
  • Make a CORS request to a remote server.   
  • Specify that you're looking for a content type of "application/json"   
  • Make sure you don't check cache or store the response in it   
  • Verify you got JSON back from the server (or maybe choose how to parse based on the data)  
  Stream Readers

  You may have noticed a call like this above:
  [code]response.text().then(function (responseText) {
    console.log(responseText);
    alert("Done using Fetch!");[/code]   What I didn't tell you before was that .text() is actually a stream reader . The TL;DR of this is that the response data is a stream of bytes that you can read from. Stream readers pull in the entire stream and parse it for you.
  There are a few methods available to you including:
  
       
  • .text() – returns the full stream as a string;   
  • .json() – returns a JSON object;   
  • .formData() – returns a FormData object, which may be useful for posting somewhere;   
  • .blob() – returns the stream as a blob , useful if you plan to do non-JS parsing with it;   
  • .arrayBuffer() – returns an array buffer, which may be useful for streaming.  
  If you need to parse the stream twice it's a problem, because once you've read it, it's empty. Fortunately there's one more method:
  
       
  • .clone() – creates an identical copy of the response.  
   Alternatively, you can parse the string manually and do what you want. You can find a good example here ( with source ), but note that this doesn't work in all browsers yet.
  What's the Catch?

  Fetch can do nearly everything that XHR can do. The two things that are missing are:
  
       
  • Fetch requests can't be canceled. This seems largely due to promises not being cancelable. Luckily, there's a spec in draft for that.   
  • Progress is difficult to track. You have to build that yourself. You can see an example of that here from this article by the Edge team.  
  That's really it. I told you this was a big improvement!
  Conclusion

   Fetch is a powerful tool you can use today (with or without the polyfill), and it's better than XHR for almost any application. You probably weren't writing XHR yourself, but if you were, life just got better. It's more likely you are using a library like jQuery to simplify your AJAX calls which won't be the case anymore. Fetch really comes into its own when we start looking into Service Workers …but that's a topic for another post.
   If you want to take a deeper dive into Fetch, the Mozilla Developer Network is the place to start.
  Happy coding!
友荐云推荐




上一篇:Essential resources for developers
下一篇:WordPress.com adds “advanced” SEO tools and it’ll make you smile
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

刘耘均 发表于 2016-10-5 01:51:24
我对楼主的敬仰如滔滔江水,绵延不绝!
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表