Vue learning notes - front and back end interaction foundation and Promise

Posted by alfoxy on Wed, 13 Oct 2021 04:55:40 +0200

1, Front and rear end interaction Foundation

1. Concept

What is front-end and back-end interaction? In fact, it refers to the process that the front end sends a request to the back end through the interface, the back end returns the corresponding data after receiving the request, and the front end makes a corresponding display or jump according to the content of the data after receiving the data. It is the process of interaction between the front end and the back end. The interface is defined and written by the back end. The front end only needs to know the request method, request address, carrying parameters and other information of the corresponding interface, and then call the interface in a specific way.

2. How the front end calls the interface

Native ajax

Code cumbersome, call trouble, not commonly used.

ajax based on jQuery

The secondary encapsulation of ajax simplifies a lot of code, but it is rarely used at present.

fetch

It is a combination of ajax + Promise, which is similar to the $. ajax() provided by jquery.

Axios (most commonly used)

It is a third-party library with simple syntax and convenient call. It is the most commonly used method for Vue based projects.

2, Promise

1. Concept

Promise is mainly used to solve the problem of callback hell. It can queue asynchronous operations so that various asynchronous operations can be executed in the order expected by our developers and return the expected results. It can also pass and operate promise between objects to help us deal with the queue.

With Promise objects, asynchronous operations can be expressed in the process of synchronous operations, avoiding layers of nested callback functions. In addition, Promise objects provide a unified API interface, making it easier to control asynchronous operations. Of course, there are some disadvantages. First of all, Promise cannot be cancelled. Once it is created, it will be executed immediately. It cannot be cancelled halfway. Secondly, if the callback function is not set, the errors thrown by Promise will not be reflected to the outside. Third, when it is in Pending status, it is impossible to know which stage it has reached (just started or about to be completed).

promise object represents an asynchronous operation. It has three states: ① pending: initial state. ② Fully: the operation is completed. ③ rejected: operation failed.

2. Basic use

 <script type="text/javascript">
    /*
     1. Promise Basic use
           We use new to build a promise. The promise constructor receives a parameter, which is a function. The content of the function body is the asynchronous task to be executed, and passes in two parameters: resolve and reject, which respectively represent the callback function after the successful execution of the asynchronous operation and the callback function after the failure of the asynchronous operation
    */
    var p = new Promise(function(resolve, reject){
      //2. Create asynchronous task setTimeout here
      setTimeout(function(){
        var flag = false;
        if(flag) {
          //3. Normal conditions
          resolve('hello');
        }else{
          //4. Abnormal conditions
          reject('Error ');
        }
      }, 100);
    });
    //  5 after the promise instance is generated, you can use the then method to specify the callback functions in the resolved state and reject state 
    p.then(function(data){
        // The first function corresponds to resolve
      console.log(data)
    },function(info){
        // The second function corresponds to reject
      console.log(info)
    });
  </script>

3. Send ajax request based on promise

① Send a single ajax request
/*
      Send Ajax request based on Promise
    */
    function queryData(url) {
      var p = 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 conditions
            resolve(xhr.responseText);
          }else{
            // Handling exceptions
            reject('Server error');
          }
        };
        xhr.open('get', url);
        xhr.send(null);
      });
      return p;
    }
	// Call Promise object
    queryData('http://localhost:3000/data').then(function(data){
         console.log(data);
    },function(info){
         console.log(info)
    });
② Send multiple ajax requests (resolve callback)
    /*
      Send Ajax request based on Promise
    */
    function queryData(url) {
      var p = 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 conditions
            resolve(xhr.responseText);
          }else{
            // Handling exceptions
            reject('Server error');
          }
        };
        xhr.open('get', url);
        xhr.send(null);
      });
      return p;
    }

    // Send multiple ajax requests and guarantee the order
    queryData('http://localhost:3000/data').then(function(data){
        console.log(data)
        // The following then receives the value returned by the promise object
        return queryData('http://localhost:3000/data1');
      })
      .then(function(data){
        console.log(data);
        // The following then receives the value returned by the promise object
        return queryData('http://localhost:3000/data2');
      })
      .then(function(data){
        console.log(data)
      });

4. Return value of Promise's then() function

In the then method, you can directly return Promise object or return data. You can receive data in the following then.

  // Take the above code as an example
  // Send multiple ajax requests and guarantee the order
    queryData('http://localhost:3000/data').then(function(data){
        console.log(data)
        // The following then receives the value returned by the promise object
        return queryData('http://localhost:3000/data1');
      })
      .then(function(data){
        console.log(data);
        // The following then receives the 'aaa' data
        return 'aaa';
      })
      .then(function(data){
        console.log(data) // aaa
      });

5. Promise's basic API

Instance method:

① Then (function 1, [function 2])

This method is used to receive the results of asynchronous task execution. If the parameter has only one function, the function only accepts the results of the correct execution of the asynchronous task. If there are two parameters, the first function receives the correct result and the second function receives the wrong result. then() is the most commonly used.

② Catch (function)

This method is used to receive the result of asynchronous task execution error. When then() only receives the correct result, the wrong result is received in this method. Not often.

③ Finally (function)

This method is called whether the asynchronous task is executed correctly or incorrectly. Not often.

Case code:
    /*
      Promise Common API instance methods
    */
    // console.dir(Promise);
    function foo() {
      return new Promise(function(resolve, reject){
        setTimeout(function(){
          //resolve(123);
          reject('error');
        }, 100);
      })
    }
	// The first way to write 
    // foo()
    //   .then(function(data){
    //     console.log(data)
    //   })
    //   .catch(function(data){
    //     console.log(data)
    //   })
    //   .finally(function(){
    //     console.log('finished')
    //   });

    // The second way to write
    // The two expressions are equivalent
    foo()
      .then(function(data){
        console.log(data)
      },function(data){
        console.log(data)
      })
      .finally(function(){
        console.log('finished')
      });

Object method:

① all()

This method is used to execute multiple promise object instances and return the results of these object instances at the same time. The parameter is an array, and the array element is the promise object to be executed (if it is not a promise, the item will be converted to a promise with Promise.resolve). The returned result is also an array. The array element is the execution result of the promise object instance, and the order corresponds to the order of the parameter array one by one. The returned result of this method must be returned after the last asynchronous task is executed.

② race()

Similar to the all() method, this method is also used to execute multiple promise object instances. The difference is that the return result of this method is only the result of the first promise object instance at the end of execution, and the results of other object instances are discarded.

Case code:
    /*
      Promise Common 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 conditions
            resolve(xhr.responseText);
          }else{
            // Handling 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 the returned results one by one ["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 and P3 are still executing, but the execution results will be discarded.
      console.log(result) // "HELLO TOM"
    })

Topics: Vue Promise