Front and back interaction (Promise, fetch, axios, async / await usage)

1.Promise overview

Promise is a solution of asynchronous programming. Syntactically, promise is an object from which messages of asynchronous operations can be obtained.

1.2 advantages of promise:

1.2.1. It can avoid nesting of multi-layer asynchronous calls (callback hell)

1.2.2. Promise object provides concise API, which makes it easier to control asynchronous operation.

1. Basic use of 3promise

  var p = new Promise(function(resolve, reject) {
        // Handle asynchronous tasks here
        // Call resolve on success
        // Call reject on failure
      });

      p.then(
        function(ret) {
          // Get normal results from resolve
        },
        function(ret) {
          // Get the wrong information from reject
        }
      );

1.4 processing Ajax requests based on Promise

function QueryData() {
        var p = new Promise(function(resolve, reject) {
          var xhr = new XMLHttpRequest();
          xhr.onreadystatechange = function() {
            if (xhr.readyState !== 4) return;
            if (xhr.readyState == 4 && shr.status == 200) {
              // Deal with normal conditions
              resolve(xhr.response);
            } else {
              // Handling exceptions
              reject("Server error");
            }
          };
          xhr.open("get", url);
          xhr.send(null);
        });
        return p;
      }

      QueryData("http://localhost:3000/data").then(
        function(data) {
          console.log(data);
        },
        function(info) {
          console.log(info);
        }
      );

1.5 use the following code to send multiple Ajax requests

  QueryData(url)
        .then(function(data) {
          return QueryData(url);
        })
        .then(function(data) {
          return QueryData(url);
        })
        .then(function(data) {
          return QueryData(url);
        });

Function return value in 1.6 then parameter

1. Return Promise instance object (the returned instance object will call the next then)

2. Return the normal value (the returned normal value will be directly passed to the next then and received through the parameter of the function in the then parameter)

1.7 API s commonly used by promise

1.7.1. Example method

p.then() gets the correct result for the asynchronous task

p.catch() gets exception information

p.finally() will execute whether it succeeds or not

1.7.2. Object method

Promise.all() processes multiple asynchronous tasks concurrently, and the results can only be obtained after all tasks are completed

Promise.race() processes multiple asynchronous tasks concurrently, and results can be obtained as long as one task is completed

 

2. Basic use of fetch

fetch("http://loaclhost:3000/data")
        .then(function(data) {
          // The text() method, part of the fetchAPI, returns the Promise instance object, which is used to get the data returned in the background
          return data.text();
        })
        .then(function(data) {
          console.log(data);
        });

2.1 parameter passing in get request mode

fetch("http://loaclhost:3000/data?id=123")
        .then(function(data) {
          // The text() method, part of the fetchAPI, returns the Promise instance object, which is used to get the data returned in the background
          return data.text();
        })
        .then(function(data) {
          console.log(data);
        });

2.2 parameter passing in post request mode

fetch("http://loaclhost:3000/data", {
        methods: "post",
        body: "username=lisi&password=123",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded"
        }
      })
        .then(function(data) {
          // The text() method, part of the fetchAPI, returns the Promise instance object, which is used to get the data returned in the background
          return data.text();
        })
        .then(function(data) {
          console.log(data);
        });

3. Basic usage of Axios

      axios.get("http://loaclhost:3000/data").then(ret => {
        // The data property name is fixed, which is used to get the data of the background response
        console.log(ret.data);
      });

3.1GET request mode parameter passing

1. Directly pass parameters through url address.

2. Pass parameters through params option.

axios
        .get("http://loaclhost:3000/data", {
          params: {
            id: 123
          }
        })
        .then(ret => {
          // The data property name is fixed, which is used to get the data of the background response
          console.log(ret.data);
        });

3.2 parameter passing in post request mode (json data is passed by default)

  axios
        .post("http://loaclhost:3000/datapost", {
            id: 123,
            username:'ww'
        })
        .then(ret => {
          // The data property name is fixed, which is used to get the data of the background response
          console.log(ret.data);
        });

3.3 axios response results

Main properties of response results:

1.data: data returned from the actual response

2.headers: response header information

3.status: response status code

4. statusText: response status information

3.4 interceptors

3.4.1 request interceptor

axios.interceptors.request.use(
        function(config) {
          config.headers.mytoken = "nihao";
          return config;
        },
        function(err) {
          //  Handle error messages here
          console.log(err);
        }
      );

3.4.2 response interceptor (process data before obtaining data)

 axios.interceptors.response.use(
        function(res) {
          // Processing returned data
          return res;
        },
        function(err) {
          //  Handle error messages here
          console.log(err);
        }
      );

4. Basic usage of async / await

 async function QueryData(id) {
        const ret = await axios.get("http://loaclhost:3000/data");
        return ret;
      }

      QueryData.then(ret => {
        console.log(ret);
      });

 

63 original articles published, 46 praised, 8831 visited
Private letter follow

Tags: axios Programming JSON

Posted on Sun, 02 Feb 2020 03:07:49 -0500 by Mesden