Interface call mode

  • Native ajax
  • Jquery-based Ajax
  • fetch
  • axios

asynchronous

  • JavaScript execution environment is “single threaded”
  • The so-called single thread refers to that there is only one thread in the JS engine responsible for interpreting and executing JavaScript code, that is, only one task can be completed at a time, and the next task can be executed after the completion of this task, which will “block” other tasks. This task can be called the main thread
  • Asynchronous mode can perform multiple tasks together
  • JS common asynchronous calls
    • Timing of any
    • ajax
    • Event functions

promise

  • Mainly solve the problem of asynchronous deep nesting
  • Promise provides a concise API to make asynchronous operations easier
 
  <script type="text/javascript">
    We use new to build a Promise. The constructor for a Promise takes one argument, which is the function, and passes in two arguments: Resolve and reject indicate the callback function */ after an asynchronous operation succeeds and */ after an asynchronous operation fails


    var p = new Promise(function(resolve, reject){
      //2. This is used to implement the asynchronous task setTimeout
      setTimeout(function(){
        var flag = false;
        if(flag) {
          //3. Normal condition
          resolve('hello');
        }else{
          //4. Abnormal condition
          reject('Wrong'); }},100);
    });
    // 5 After the Promise instance is generated, the then method can be used to specify the Resolved and REJECT callback functions
    // In the THEN method, you can return the data directly instead of the Promise object, and receive the data in the later THEN
    p.then(function(data){
      console.log(data)
    },function(info){
      console.log(info)
    });
  </script>
Copy the code

Send Ajax requests based on promises

 
  <script type="text/javascript">Var p = new Promise(function(resolve, resolve)); reject){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState ! = 4) return; Resolve (xhr.responsetext); if(xhr.readyState == 4 &&xhr.status == 200) {# 1.2 resolve(xhr.responsetext); }else{# 1.3 reject(' server error '); }}; xhr.open('get', url); xhr.send(null); }); return p; } # In the then method, you can also return data directly instead of a Promise object, In the back of the then can receive data queryData (' http://localhost:3000/data '). Then (function (data) {the console. The log (data) # 1.4 want to continue the chain programming Need to be return return queryData('http://localhost:3000/data1'); }) .then(function(data){ console.log(data); return queryData('http://localhost:3000/data2'); }) .then(function(data){ console.log(data) });</script>
Copy the code

Promise the basic API

Instance methods

.then()
  • Get correct results for asynchronous tasks
.catch()
  • Obtaining exception Information
.finally()
  • Success or failure (not formal criteria)
  
  <script type="text/javascript">// / console.dir(Promise); function foo() { return new Promise(function(resolve, reject){ setTimeout(function(){ // resolve(123); reject('error'); }, 100); }) } // foo() // .then(function(data){ // console.log(data) // }) // .catch(function(data){ // console.log(data) // }) // .finally(function(){ // console.log('finished') // }); / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - / / two writing is the equivalent of foo (). Then (function (data) {# asynchronous tasks right results the console. The log (data)}, function (data) { Console.log (data)}) finally(function(){console.log('finished')});</script>
Copy the code

A static method

.all()
  • Promise.allMethod takes an array of objects (P1, P2, p3) that are instances of a Promise. (If it is not a Promise, the item will be used.Promise.resolveConvert to a promise). Its state is determined by the three promise instances
.race()
  • Promise.raceThe method also takes an array as an argument. When the state of one instance in P1, P2, p3 changes (becomesfulfilledorrejected), and the state of P changes accordingly. And pass the return value of the first promise that changed the state to p’s callback

  <script type="text/javascript">
    /* Promise uses API- object methods */
    // console.dir(Promise)
    function queryData(url) {
      return new Promise(function(resolve, reject){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
          if(xhr.readyState ! =4) return;
          if(xhr.readyState == 4 && xhr.status == 200) {
            // Handle normal situations
            resolve(xhr.responseText);
          }else{
            // Handle exceptions
            reject('Server error'); }}; xhr.open('get', url);
        xhr.send(null);
      });
    }

    var p1 = queryData('http://localhost:3000/a1');
    var p2 = queryData('http://localhost:3000/a2');
    var p3 = queryData('http://localhost:3000/a3');
     Promise.all([p1,p2,p3]).then(function(result){
       // the parameters [p1,p2,p3] in all correspond to ["HELLO TOM", "HELLO JERRY", "HELLO SPIKE"]
       console.log(result) //["HELLO TOM", "HELLO JERRY", "HELLO SPIKE"]
     })
    Promise.race([p1,p2,p3]).then(function(result){
      // Since p1 executes faster, Promise's then() will get the result 'p1'. P2,p3 continue to execute, but the execution results will be discarded.
      console.log(result) // "HELLO TOM"
    })
  </script>
Copy the code

fetch

  • The Fetch API is the new Ajax solution where Fetch returns promises
  • Fetch is not a further encapsulation of Ajax, but rather native JS, without using XMLHttpRequest objects.
  • The fetch (url, options). Then ()
  <script type="text/javascript">
    Fetch (url).then() The first parameter of the request path Fetch returns a Promise, so we can use then to get the result of a successful request */
    fetch('http://localhost:3000/fdata').then(function(data){
      The text() method, which is part of fetchAPI, returns a Promise instance object that gets the data returned in the background
      return data.text();
    }).then(function(data){
      // In this then we can get the final data
      console.log(data);
    })
  </script>
Copy the code

HTTP requests in the FETCH API

  • The fetch (url, options). Then ()
  • HTTP protocol, it provides us with many methods, such as POST, GET, DELETE, UPDATE, PATCH and PUT
    • The default is a GET request
    • You need to specify the corresponding method in the Options object. Method: The method used in the request
    • For post and normal requests, you need to set headers and body in options
   <script type="text/javascript">/* Fetch API calls interface pass parameter */ #1.1 GET parameter pass - traditional URL through URL? In the form of spread and the fetch (' http://localhost:3000/books? Id =123', {# get request can be omitted without writing the default is get method: 'get'}). Then (function(data) {# return data.text(); }). Then (function(data) {# console.log(data)}); # 1.2 the GET parameter passing in the form of a restful URL in the form of pass/passing parameters Id = 456 and configuration id the background about the fetch (' http://localhost:3000/books/456 ', }). Then (function(data) {return data.text(); }).then(function(data) { console.log(data) }); Way # 2.1 the DELETE request parameter passing DELETE id is the id = 789 the fetch (' http://localhost:3000/books/789 '{method: 'delete' }) .then(function(data) { return data.text(); }).then(function(data) { console.log(data) }); # 3 POST request pass and the fetch (' http://localhost:3000/books' {method: "POST", # 3.1 pass data body: 'uname=lisi&pwd=123', # 3.2 Headers: {' content-type ': 'application/x-www-form-urlencoded' } }) .then(function(data) { return data.text(); }).then(function(data) { console.log(data) }); # transmit and fetch POST request (' http://localhost:3000/books' {method: "POST", the body: JSON. Stringify ({uname: 'Joe Smith, PWD: '456' }), headers: { 'Content-Type': 'application/json' } }) .then(function(data) { return data.text(); }).then(function(data) { console.log(data) }); # transmit and modify the PUT request id is 123, fetch (' http://localhost:3000/books/123 '{method:' PUT 'body: JSON. The stringify ({uname: }}). Then (function(data) {return data.text(); }).then(function(data) { console.log(data) });</script>
Copy the code

Format of the response in fetchAPI

  • Fetch is used to obtain data. If the response is returned normally, the first thing we see is a Response object, which includes a bunch of returned original bytes. After receiving these bytes, we need to call methods to convert them into data in the corresponding format, such asJSON.BLOBorTEXT, etc.
    /* Fetch the data format of the response result */
    fetch('http://localhost:3000/json').then(function(data){
      // return data.json(); // Convert the obtained data to an object using JSON
      return data.text(); // // converts the obtained data to a string
    }).then(function(data){
      // console.log(data.uname)
      // console.log(typeof data)
      var obj = JSON.parse(data);
      console.log(obj.uname,obj.age,obj.gender)
    })

Copy the code

axios

  • HTTP client based on Promise for browsers and Node.js
  • Supports browsers and Node.js
  • Supporting promise
  • Intercepts requests and responses
  • Automatically convert JSON data
  • Ability to transform request and response data

Basic usage of axios

  • Get and DELETE requests pass parameters
    • Through the traditional URL with? Pass parameters in the form of
    • Restful pass parameters
    • Pass parameters through params
  • Post and PUT requests pass parameters
    • Pass parameters through options
    • Pass parameters through URLSearchParams
# 1. Send a get request axios. Get (' http://localhost:3000/adata '). Then (function (ret) {# get ret is an object All objects within the data property of ret / / // console.log(ret. Data) console.log(ret)}) # 2. In the form of passing parameters axios. Get (' http://localhost:3000/axios? Id =123'). Then (function(ret){console.log(ret. Data)}) # 2.2 restful Axios. Get (' http://localhost:3000/axios/123 '). Then (function (ret) {the console. The log (ret) data)}) # 2.3 through the params form passing parameters axios.get('http://localhost:3000/axios', { params: { id: 789}}). Then (function(ret){console.log(ret. Data)}) #3 AXIos delete requests pass parameters in the same form as get requests axios.delete('http://localhost:3000/axios', { params: { id: 111}}).then(function(ret){console.log(ret. Data)}) # 4 Axios post request # 4.1 pass parameters through options axios.post('http://localhost:3000/axios', { uname: 'lisi', pwd: Var params = new URLSearchParams(); params.append('uname', 'zhangsan'); params.append('pwd', '111'); axios.post('http://localhost:3000/axios', Params).then(function(ret){console.log(ret. Data)} axios.put('http://localhost:3000/axios/123', { uname: 'lisi', pwd: 123 }).then(function(ret){ console.log(ret.data) })Copy the code

Axios global configuration

# configure the common request header axios.defaults.baseURL = 'https://api.example.com'; Axios.defaults. timeout = 2500; # configuration public request header axios.defaults.headers.com mon [' Authorization '] = AUTH_TOKEN; # configuration of public post the content-type axios. Defaults. Headers. Post [' the content-type '] = 'application/x - WWW - form - urlencoded';Copy the code

Axios interceptor

  • Request interceptor
    • The purpose of a request interceptor is to do something before a request is sent
      • For example, add token to each request body, which makes it easy to change later
  • Response interceptor
    • The purpose of a response interceptor is to do something after receiving a response
      • For example, if the server login status is invalid and you need to log in to the server again, the login page is displayed
# 1. Request interceptor axios. Interceptors. Request. Use (function (config) {the console. The log (config. Url) # 1.1 any request after this step Before sending a request do config.headers.mytoken = 'nihao'; Return config; }, function(err){#1.3 do something about the error console.log(err)}) #2. Response interceptor axios. Interceptors. Response. Use (function (res) {# 2.1 in receiving the response do var data = res. The data; return data; }, function(err){#2.2 do something about response error console.log(err)})Copy the code

Async and await

  • Async precedes functions as a keyword
    • Any oneasyncAll functions implicitly return onepromise
  • awaitThe keyword can only be usedasyncUsed in a function defined by
    • Await can be followed directly by a Promise instance object
    • The await function cannot be used alone
  • Async /await makes asynchronous code look and behave more like synchronous code
Async function queryData() {# 1.2 await keyword can only be used in functions defined using async Var ret = await new Promise(function(resolve, reject){setTimeout(function(){resolve('nihao')},1000); }) // console.log(ret.data) return ret; Then (function(data){console.log(data)}) #2. async Function to handle multiple asynchronous functions axios.defaults.baseURL = 'http://localhost:3000'; Async function queryData() {# 2.1} var info = await axios.get('async1'); Var ret = await axios.get('async2? info=' + info.data); return ret.data; } queryData().then(function(data){ console.log(data) })Copy the code

The Book List case

1. Interface-based case – Get book list

  • Import AXIOS to send ajax
  • Render the obtained data onto the page
  <div id="app">
        <div class="grid">
            <table>
                <thead>
                    <tr>
                        <th>Serial number</th>
                        <th>The name of the</th>
                        <th>time</th>
                        <th>operation</th>
                    </tr>
                </thead>
                <tbody>
                    <! -- 5. Render data from Books to page -->
                    <tr :key='item.id' v-for='item in books'>
                        <td>{{item.id}}</td>
                        <td>{{item.name}}</td>
                        <td>{{item.date }}</td>
                        <td>
                            <a href="">Modify the</a>
                            <span>|</span>
                            <a href="">delete</a>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    <script type="text/javascript" src="js/vue.js"></script>1. Import axios<script type="text/javascript" src="js/axios.js"></script>
    <script type="text/javascript">/* library - add books */ # 2 configure the public URL address to simplify the following call method axios.defaults.baseURL = 'http://localhost:3000/'; axios.interceptors.response.use(function(res) { return res.data; }, function(error) { console.log(error) }); var vm = new Vue({ el: '#app', data: { flag: false, submitFlag: false, id: '', name: '', books: [] }, methods: {# 3 define a method to send Ajax # 3.1 Use async to make asynchronous code write queryData synchronously: Async function() {var ret = await axios.get('books'); // this.books = ret.data; Get ('books'); this.books = await axios.get('books'); }}, mounted: function() {# 5 mounted: function() {this.queryData(); }});</script>
Copy the code

2 Adding books

  • Get the data entered by the user and send it to the background
  • Render the latest data to the page
methods: { handle: Async function(){if(this.flag) {this.books.some((item) => {if(item.id == this.id) {if(item.id == this.id) { item.name = this.name; Return true; }}); this.flag = false; }else{# 1.1 Sending ajax requests in the previously wrapped Handle method # 1.2 Simplifying operations with async and await requires adding async var ret = await in front of function axios.post('books', { name: If (ret.status == 200) {this.queryData() {this.queryData(); }} // Clear the form this.id = "; this.name = ''; }},Copy the code

3 Verify that the book name exists

  • Send a request to verify that the schema already exists before adding the book
  • If not, add the book name to the background
    • You only need to change the value of submitFlag to check whether the book exists
 watch: {
        name: async function(val) {
          // Verify that the book name already exists
          // var flag = this.books.some(function(item){
          // return item.name == val;
          // });
          var ret = await axios.get('/books/book/' + this.name);
          if(ret.status == 1) {
            // The book name exists
            this.submitFlag = true;
          }else{
            // The book name does not exist
            this.submitFlag = false; }}},Copy the code

4. Edit books

  • Query the book that you want to edit based on the current book ID
  • You need to determine whether to add or edit based on the status bits
methods: { handle: Var ret = await axios.put('books/' + this.id, {name: {name: {name: {}} this.name }); If (ret. Status == 200){#4.4 Reload list data this.queryData(); } this.flag = false; }else{// add books var ret = await axios.post('books', {name: This.name}) if(ret.status == 200) {// Reload list data this.queryData(); }} // Clear the form this.id = "; this.name = ''; }, toEdit: async function(id){#4.1 flag status bits used to distinguish between editing and adding operations this.flag = true; Var ret = await axios.get('books/' + id); this.id = ret.id; this.name = ret.name; },Copy the code

5 Deleting books

  • The id books to be deleted are passed to the background in the form of parameters
   deleteBook: async function(id){
          // Delete the book
          var ret = await axios.delete('books/' + id);
          if(ret.status == 200) {
            // Reload the list data
            this.queryData(); }}Copy the code