网络科技

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

[其他] Fetch – Modern Async Server Calls

[复制链接]
不见不散 发表于 2016-10-4 23:15:48
185 1
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:
  1. $("#basicjQueryButton").on("click", function() {
  2.     // Loading the jQuery code
  3.     $.get("https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js", function(data) {
  4.         console.log(data);
  5.         alert("Done using jQuery!");
  6.     });
  7. });
复制代码
  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

Fetch – Modern Async Server Calls

  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:
  1. LoadMyData()
  2.     .then(ProcessMyData)
  3.     .then(DoSomethingElse)
  4.     .catch(HandleError);
复制代码
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:
  1. response.text().then(function (responseText) {
  2.     console.log(responseText);
  3.     alert("Done using Fetch!");
复制代码
  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!
刘耘均 发表于 2016-10-5 01:51:24
我对楼主的敬仰如滔滔江水,绵延不绝!
回复 支持 反对

使用道具 举报

我要投稿

推荐阅读


回页顶回复上一篇下一篇回列表
手机版/c.CoLaBug.com ( 粤ICP备05003221号 | 粤公网安备 44010402000842号 )

© 2001-2017 Comsenz Inc.

返回顶部 返回列表