A preface

In the traditional Ajax era, web requests such as APIS were made through XMLHttpRequest or encapsulated frameworks, but the configuration and invocation methods were confusing and unfriendly to beginners. Fetch, which we introduced today, provides a better alternative that not only provides a simple, logical way to Fetch resources asynchronously across a network, but can also be easily used by other technologies, such as Service Workers.

Second, compare with Ajax

Using Ajax to request JSON data looks like this:

var xhr = new XMLHttpRequest();
xhr.open('GET', url/file,true);
xhr.onreadystatechange = function() {
   if(xhr.readyState==4){
        if(xhr.status==200){ var data=xhr.responseText; console.log(data); }}; xhr.onerror =function() {
  console.log("Oh, error");
};
xhr.send();
Copy the code

Similarly, we use fetch to request JSON data:

Fetch (url).then(response => response.json()).then(data => console.log(data)thenCatch (err => console.log("Oh, error", err))// Call catch when reject is executedCopy the code

From the comparison of the two, fetch code is much simpler and the business logic is clearer, making the code easy to maintain and more readable. In a word, Fetch has the following advantages:

1. Concise syntax, more semantic, clearer business logic

2. Support async/await based on standard Promise implementation

3. Isomorphic convenience, useisomorphic-fetch

Introduction of three Promise

Since the Fetch API is designed based on Promise, let’s take a brief look at the Promise workflow to better understand Fetch.

The FETCH method returns a Promise object, and by the nature of the Promise Api, FETCH can easily string together processing logic using the THEN method, Using the promise.resolve () or promise.reject () methods returns a Promise confirming or denying the outcome, respectively, calling the next then or catch. If an error occurs in a statement in then, it will also jump to catch.

Request common data formats

Next, you’ll see how to use FETCH to request local text data, local JSON data, and a network interface. In fact, compared with Ajax operation, much simpler!

//HTML section <div class="container">
    <h1>Fetch Api sandbox</h1>
    <button id="button1"</button> <button id="button2"</button> <button id="button3"</button> <br>< div id="output"></div>
  </div>
  <script src="app.js"></script>
Copy the code

1. Fetch requests local text data

A test.txt file is available locally, and the following code can be used to retrieve the data and display it on the page.

document.getElementById('button1').addEventListener('click',getText);
function getText(){
  fetch("test.txt"). Then ((res) = > res. The text ()) / / note: this is a res. The text (). Then (data = > {the console. The log (data); document.getElementById('output').innerHTML = data;
      })
      .catch(err => console.log(err));
}
Copy the code

2. Fetch requests local JSON data

There is posts.json data locally, and instead of requesting native text, you have to get it through forEach and render it on the page.

document.getElementById('button2').addEventListener('click',getJson);
function getJson(){
  fetch("posts.json")
      .then((res) => res.json())
      .then(data => {
        console.log(data);
        let output = ' ';
        data.forEach((post) => {
          output += `<li>${post.title}</li>`;
        })
        document.getElementById('output').innerHTML = output;
      })
      .catch(err => console.log(err));
}
Copy the code

3. Fetch requests the network interface

Retrieve data from https://api.github.com/users, is similar to the method to obtain local JSON, after get the data, also to be processed

document.getElementById('button3').addEventListener('click',getExternal);
function getExternal(){
  // https://api.github.com/users
  fetch("https://api.github.com/users")
      .then((res) => res.json())
      .then(data => {
        console.log(data);
        let output = ' ';
        data.forEach((user) => {
          output += `<li>${user.login}</li>`;
        })
        document.getElementById('output').innerHTML = output;
      })
      .catch(err => console.log(err));
}
Copy the code