Promise asynchronous programming

Promise asynchronous programming

 

 A. Promise usage

1. Promise basic usage

Promise instantiated object constructor transfer function, the function for processing asynchronous tasks

and reject resolve two parameters for processing the successes and failures in both cases, and obtaining processing results by p.then

When an incoming call then it can only deal with normal function, not a function of incoming unusual circumstances, that is only successful treatment cases

 / *   
   We use the new constructor to build a Promise Promise receive a parameter is a function and pass two parameters: 
   Resolve, Reject, respectively, after the callback function callback and asynchronous operations performed after the successful implementation of asynchronous operation failed     * / var P = new new Promise ( function (Resolve, Reject) {
       // 2. here asynchronous tasks for implementing the setTimeout 
      the setTimeout ( function () {
         var In Flag = to false ;
         IF (In Flag) {
           // 3. normally 
          resolve ( 'Hello' ); 
       } the else {
           // 4. abnormality 
          Reject ( 'wrong' ); 
        } 
      } 100
    ); 
    }); 
    //   later. 5 Promise instance generation, and can specify the resolved state reject state by callback method then 
    //   in the process then, you can not directly return Promise data object, then the back of the can receive the data 
    p.then ( function (data) {
     // get the normal result from Resolve 
      the console.log (data) 
    }, function (info) { 
     // get an error message from the Reject 
     the console.log (info) 
    });
/ * 
      Based Promise Ajax requests 
    * / 
    function the queryData (URL) {
       var P = new new Promise ( function (Resolve, Reject) {
         var XHR = new new the XMLHttpRequest (); 
        xhr.onreadystatechange = function () {
           IF (xhr.readyState! . 4 =) return ;
           IF (xhr.readyState == == 200 is xhr.status &&. 4 ) {
             // where normal processing 
            Resolve (xhr.responseText); 
          } the else {
             // handle exceptions
            reject ( 'Server Error' ); 
          } 
        }; 
        xhr.open ( 'GET' , URL); 
        xhr.send ( null ); 
      }); 
      return P; 
    } 
    // ordinary circumstances 
    // the queryData ( 'HTTP: // localhost : 3000 / Data ') 
    //    .then (function (Data) { 
    //      the console.log (Data); 
    //    }, function (info) { 
    //      the console.log (info) 
    //    }); 
    // = =========================== 
    // send a plurality of requests and to ensure that the order ajax 
    //If the return value then a return is a normal object. The next chain then the argument is this ordinary objects, the caller is then automatically created objects promise to guarantee chained calls 
   // if the return is a promise of return the object, then the next then is processed on a the method then returns object promise 
    the queryData ( 'HTTP: // localhost: 3000 / Data' ) 
      .then ( function (Data) { 
        the console.log (Data) 
        return the queryData ( 'HTTP: // localhost: 3000 / DATAl' ) ; 
      }) 
      .then ( function (Data) { 
        the console.log (Data); 
        return the queryData ( 'HTTP: // localhost: 3000 / DATA2' ); 
      }) 
      .then ( function (Data) { 
        the console.log (Data) 
      });

 

 2. In addition to abnormality in the then passed two functions, can also be changed to deal .catch, the same effect

  function foo () {
       return  new new Promise ( function (Resolve, Reject) { 
        the setTimeout ( function () {
           // Resolve (123); 
          Reject ( 'error' ); 
        }, 100 ); 
      }) 
    } 
    foo () 
      .then ( function (Data) {
        // get the correct result of the asynchronous task 
        the console.log (Data) 
      }) 
      . the catch ( function (Data) {
        // Get the abnormality information 
        the console.log (Data) 
      }) 
      .the finally ( function () {
        // success will be executed (not an official standard) 
        the console.log ( 'Finished' ) 
      });

 

 3. Promise Common Object Methods

function the queryData (URL) {
       return  new new Promise ( function (Resolve, Reject) {
         var XHR = new new the XMLHttpRequest (); 
        xhr.onreadystatechange = function () {
           IF ! (= xhr.readyState. 4) return ;
           IF (= xhr.readyState == 200 is xhr.status. 4 && = ) {
             // where normal processing 
            Resolve (xhr.responseText); 
          } the else {
             // handle exceptions 
            Reject ( 'server error " ); 
          } 
        };
        xhr.open ( 'GET' , URL); 
        xhr.send ( null ); 
      }); 
    } 

    var P1 = the queryData ( 'HTTP: // localhost: 3000 / A1' );
     var P2 = the queryData ( 'HTTP: // localhost: 3000 / A2 ' );
     var P3 = the queryData (' HTTP: // localhost: 3000 / A3 ' ); 

    // all means all successfully executed asynchronously 
    //   parameters of all the [p1, p2, p3] and return The results correspond result is an array [ "HELLO TOM", "HELLO JERRY", "HELLO the SPIKE"] 
    // Promise.all ([P1, P2, P3]). the then (function (result) { 
    //    the console.log (the Result) 
    // }) 

    // one of the fastest asynchronous race successfully executed, regardless of other 
    //Since p1 faster execution, Promise of the then () The obtained results 'P1'. p2, p3 continued to perform, but the results will be discarded. 
    Promise.race ([P1, P2, P3]). The then ( function (Result) { 
      the console.log (Result) 
    })

 

 

Two. Fetch Interface Usage (with the server to interact Get, Post)

 

Three. Axios Interface Usage (with the server to interact Get, Post)

1. This interface need to import files corresponding js

 

 

Four. Async / await allow asynchronous code look, behave more like synchronization code

 1. await keywords can only be used in functions defined using async

 2. await behind direct instance of an object with a Promise 

 3. Any async function will return an implicit promise that we can use then be chained program 

 4. After the current added await await the result will be performed later after returning code 

    async function queryData() {
      var ret = await new Promise(function(resolve, reject){
        setTimeout(function(){
          resolve('nihao')
        },1000);
      })
      // console.log(ret.data)
      return ret;
    }
    queryData().then(function(data){
      console.log(data)
    })

 

Guess you like

Origin www.cnblogs.com/dlm17/p/12441022.html