Traditional Ajax is dead, Fetch eternal life

Source: Internet
Author: User

Forgive me for doing it once title party, Ajax will not die, traditional Ajax refers to XMLHttpRequest (XHR), the future is now replaced by the Fetch.

Recently, Ali a TENS PV data products all moved by the JQuery $.ajax , the Fetch online one months since the operation is very stable. It turns out that it is possible to use Fetch in a production environment for browsers above ie8+.

Since the Fetch API is based on the Promise design, it is necessary to learn the Promise first and recommend reading the MDN Promise tutorial. The old browser does not support Promise and requires the use of Polyfill es6-promise.

This article is not a Fetch API paste, in fact, is about asynchronous processing and Promise. The Fetch API is simple enough to see the document quickly learned. Recommended MDN fetch tutorials and the Universal WHATWG Fetch specification

Why Fetch

XMLHttpRequest is a poorly designed API that does not conform to the principles of separation of concerns (separation of concerns), is very confusing in configuration and invocation, and the event-based asynchronous model does not write modern promise,generator/ Yield,async/await friendly.

The appearance of Fetch is to solve the problem of XHR, take an example to illustrate:

Sending a JSON request using XHR is typically the case:

var xhr=NewXMLHttpRequest ();XHR. open ( ' Get ", url); responsetype =  JSON XHR. onload = function () {console.log (xhr. response);}; XHR. onerror = function () {console.log ( "Oops, ErrorXHR. send ();               

After using Fetch, it looks a little better.

Fetch (URL). Then (function (response) {  response.  JSON ();}). Then (function (console).  log (data);}). catch (function (console).  Log ("Oops, Error");});              

After using the ES6 arrow function:

Fetch (URL). Then (response.  JSON ()). Then (console.  Log (data)). catch (console.  Log ("Oops, Error", e))          

It looks a lot better now, but the Promise is still Callback, and it's a bit odd that Promise uses catch methods to do error handling. Don't worry, use async/await to make the final optimization:

Note: Async/await is a very new API, belonging to ES7, which is still in Stage 1 (proposed) phase, which is its complete specification. Using Babel to turn on runtime mode, you can compile async/await without pain to ES5 code. You can also use regenerator directly to compile to ES5.

try {  fetch (URL);  Response. Console. Console. log ("Oops, Error", e);} //NOTE: If you want to run this code, you need to package an async function outside       

duang~, await after use, writing asynchronous code is as cool as writing synchronous code. The await following can be followed by the Promise object, which indicates that wait Promise resolve() will continue to execute downward, and if Promise is reject() or throws an exception, it will be try...catch caught outside.

Promise,generator/yield,await/async are now and in the future JS solution asynchronous standard practice, can be used in perfect combination. This is also a big benefit of using standard Promise. Recently, the code that uses third-party Promise libraries in the project has been turned into standard Promise, preparing for the full use of async/await in the future.

In addition, fetch is also very suitable for today's popular homogeneous applications, some people based on the syntax of fetch, in the Node side based on the HTTP library implementation of the Node-fetch, and others encapsulated in the Isomorphic-fetch for homogeneous applications.

Note: isomorphism (isomorphic/universal) is the meaning of running the same set of code on the front and back end, which generally refers to the NodeJS environment.

To summarize, the main advantages of Fetch are:

    1. Simple syntax, more semantic
    2. Based on standard Promise implementation, support async/await
    3. Homogeneous and easy to use Isomorphic-fetch
Fetch Enable method

Here is the key ↓↓↓

First look at the Fetch native support rate:

Native support rate is not high, fortunately, the introduction of the following Polyfill can perfectly support ie8+:

    1. Since IE8 is ES3, it is necessary to introduce ES5 Polyfill:es5-shim, Es5-sham
    2. Introduction of Promise Polyfill:es6-promise
    3. Introduction of FETCH Probe Library: Fetch-detector
    4. Polyfill:fetch-ie8 of the introduction of fetch
    5. Optional: If you also use JSONP, introduce FETCH-JSONP
    6. Optional: Turn on Babel runtime mode and use Async/await now

The basic principle of Fetch polyfill is to detect if there is a window.fetch method and if not, implement it with XHR. This is also the practice of github/fetch, but some browsers (Chrome 45) natively support fetch, but the response in Chinese will be garbled, the foreigner is not too concerned about this problem, so I myself encapsulated fetch-detector and fetch-ie8 only in the browser stable support fetch The native Fetch is used. These libraries now have tens of millions of requests every day, absolutely reliable!

Finally, after quoting this heap of Polyfill, you can happily use Fetch. But be careful, there is a pit below:

Fetch Common Pits
    • Fetch requests are not cookies by default and need to be setfetch(url, {credentials: ‘include‘})
    • The server returns a 400,500 error code and does not reject, only the network error these causes the request to not complete, the fetch will be reject.

Actually did not mention IE, this is really unscientific, now to detail IE

IE usage Policy

All versions of IE do not support native FETCH,FETCH-IE8 will automatically use XHR to do polyfill. However, there is a problem that needs to be addressed when crossing domains.

IE8, 9 of XHR does not support CORS across domains, although provided XDomainRequest , but this thing is a toy, does not support transmission cookie! If the interface requires permission verification, or obediently use Jsonp Bar, it is recommended to use FETCH-JSONP. If there is a problem directly to mention issue, I will be the first time to solve.

The lack of Fetch and standard Promise

Since fetch is a typical asynchronous scenario, most of the problems encountered are not fetch, but are Promise. ES6 's Promise is based on the promises/a+ standard, in order to remain simple and concise, only to provide a few minimalist APIs. If you've used some bull X's asynchronous libraries, like JQuery (don't laugh), q.js, or rsvp.js, you might feel Promise too little.

No Deferred.

Deferred can be used to reduce the level of nesting when creating Promise, and it is convenient to use across methods.
ECMAScript had a Deferred proposal in 11, but was not accepted later. In fact, with Promise less than 10 lines of code can be implemented deferred:es6-deferred. Now with the Async/await,generator/yield, deferred has no use value.

No get state method: Isrejected,isresolved

The standard Promise does not provide a way to get the current state rejected or resolved. Only allow external incoming callbacks after success or failure. I think this is actually an advantage, it's a declarative interface, and it's simpler.

Some other methods are missing: always,progress,finally

Always can be implemented by repeatedly invoking methods in then and catch. Finally is similar. Progress this progress notification function has not been used, and do not know how to replace.

cannot be interrupted, no abort, terminate, OnTimeOut, or Cancel method

Fetch and Promise, once initiated, can not be interrupted, will not time out, can only wait to be resolve or reject. Fortunately, WHATWG is currently trying to solve the problem whatwg/fetch#27

Information
    • WHATWG Fetch Specification
    • Introduction to the Fetch API
    • Teach you to tame async
    • Nanyi Introduction to Async
At last

Fetch replacement XHR is only a matter of time, and now we see that many new libraries abroad are using fetch by default.

Finally, make a bold prediction: Due to the emergence of new asynchronous syntax such as async/await, third-party Promise class libraries will gradually be replaced by standard Promise, the use of Polyfill is now a more sensible approach.

Https://github.com/camsong/blog/issues/2

If you think this article is helpful to you, please click on the Star in the top right to encourage you, or click Watch Subscription

Traditional Ajax is dead, Fetch eternal life

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.