Promise

  • Internet Explorer incompatibility Exclusion (EDGE) : Handle compatibility based on Babel-Polyfill (principle: itself based on Promise–>Promise A+ specification)Promisesaplus.com/)
  • Promise, the code that manages asynchronous programming, is a design pattern (the promiser pattern) that addresses the callback hell of asynchronous programming

How did you ask before there was a promise?

In this project, our AJAX requests are both parallel and serial AJAX requests of ‘asynchronous’ requests

  • Serial: Multiple AJAX requests that are dependent on one request before the next request can be sent
  •  Callback Hell: nested callback functions within callback functions (nesting doll operations)
$.ajax({
    url:'xxx1.json'.method:'GET'.dataType:'JSON'.success(value){
      console.log('Request successful',value);
      $.ajax({
        url:'xxx2.json'.method:'GET'.dataType:'JSON'.success(value){
          console.log('Request successful',value);
          $.ajax({
            url:'xxx3.json'.method:'GET'.dataType:'JSON'.success(value){
              console.log('Request successful',value); }})}})Copy the code
  • Parallelism: Multiple AJAX requests can be sent at the same time with no dependencies between requests (typically concurrency management is required)
$.ajax({
        url'xxx1.json'.success(value) {
            console.log('First request successful :', value); }}); $.ajax({url'xxx2.json'.success(value) {
            console.log('Second request successful :', value); }}); $.ajax({url'xxx3.json'.success(value) {
            console.log('Third request successful :', value); }});Copy the code

First look Promise

const query1 = () = >{
  return new Promise(resolve= >
    $.ajax({
      url:'./data1.json'.success(value){ resolve(value); }}}))const query2 = () = >{
  return new Promise(resolve= >
    $.ajax({
      url:'./data2.json'.success(value){ resolve(value); }}}))const query3 = () = >{
  return new Promise(resolve= >
    $.ajax({
      url:'./data3.json'.success(value){ resolve(value); }}}))Copy the code

Resolve callback hell based on promises

query1()
.then(value= >{
  console.log('First request successful',value);
  return query2();
})
.then(value= >{
  console.log('Second request successful',value);
  return query3();
})
.then(value= >{
  console.log('Third request successful',value);
}) 
// ||async/await
(async function(){
  let value = await query1();
  console.log('First request successful',value);

  value = await query2();
  console.log('Second request successful',value);

  value = await query3();
  console.log('Third request successful',value); }) ();Copy the code

new Promise([executior]);

  • You must pass a function. If you don’t pass a function, an error is reported. Executior
  • The executior function takes two parameters: reslove & Reject (reslove and reject are functions)
  • When a new Promise is made, the executior function passed in will be executed immediately
  • Function to manage asynchronous programming code
let p1 = new Promise(function executior(reslove,reject){
// We manage the code of asynchronous programming. We only need to modify the state of instance P1 when AJAX request succeeds or fails, and change the result obtained from server or the cause of request failure. This is a big pity/onfulfilled. This is a big pity /onrejected. This is a big pity/onfulfilled
  $.ajax({
      url:'./data1.json'.success: function(value) {
        // The request succeeded
        resolve(value)
      },
      error: function(value) {
        // The request failed
        reject(reason)
      },
    })
  });
  p1.then(
   function onfulfilled(value){
     console.log('success',value);
   },
   function onrejected(reason){
    console.log('failure',reason); })Copy the code

THEN the chain mechanism

  • Each time the THEN method is executed, a brand new Promise instance is returned

Method to create a Promise instance

  • new Promise([executior])
  • The state and value of the instance are determined by whether the executior function executes with an error &resolve/reject
  • This is a big pity, onfulfilled,onrejected), then(onfulfilled,onrejected), the state and value of this instance will be related to the implementation of onfulfilled or onrejected. (This is a big pity, onfulfilled) The NEW instance (@new) is a NEW promise instance (@new); if the NEW instance (rejected) returns a NEW promise instance (@new); if the NEW instance (rejected) returns a NEW promise instance (@new); if the NEW instance (@new) returns a NEW promise instance (@new); This is a big pity. If the method return value is not a new instance, THEN the state is fulfilled, and the value is the return value of the function
  • Promise.resolve([value]): Directly create an instance whose status is success and value is value
  • Promise.reject([reason]): Directly create an instance whose state is failure and value is Reason
  • Promise.all([promise,promise,…] ) : listening passed in the array, each a promise the status of the instance, when all the instance state is successful, the overall return to the status of the instance is successful, value is an array, containing all the results of the example: if one instance of a failure, the overall return is failure, the instance of the value of a failure is that the value of the promise
  • Promse.race: a Promise. Race ([P1, P2, P3]) returns the fastest result, regardless of whether the result itself is a success or a failure.
// Print what? Request succeeded 100 Request failed 0 Request succeeded NO
let p1 = new Promise((resolve, reject) = > {
  resolve(100);
});
let p2 = p1.then(value= > {
  console.log('Request successful :', value);
  return new Promise((_, reject) = > {
      reject(0);
  });
}, reason= > {
  console.log('Request failed :', reason);
  return new Promise((resolve) = > {
      resolve(100);
  });
});
let p3 = p2.then(value= > {
  console.log('Request successful :', value);
  return 'OK';
}, reason= > {
  console.log('Request failed :', reason);
  return 'NO';
});
p3.then(value= > {
  console.log('Request successful :', value);
}, reason= > {
  console.log('Request failed :', reason);
});

Copy the code

THEN’s “penetration/continuation” mechanism

  • If onfulfilled or onRejected is not fulfilled, the Promise will be automatically completed internally
// Request success 100 is deferred
new Promise(resolve= >{
  resolve(100);
}).then(null/* equals value=>{return,value} */.reason= >{
  console.log('Request failed',reason);
}).then(value= >{
  console.log('Request successful',value)
})

Copy the code
// Failed state Deferred request failed 100
new Promise((_,reject) = >{
  reject(0)}/* reason =>{throw reason} */).then(value= >{
  console.log('Request successful',value);
}/* reason =>{throw reason} */).then(value= >{
  console.log('Request successful',value);
}).then(null.reason= >{
  console.log('Request failed',reason);
})
Copy the code

Promise.prototype.cath: handles state failures (added at the end)

  • .then(null, failed state) is equivalent to.catch
new Promise((_,reject) = >{
  reject(0)}/* reason =>{throw reason} */).then(value= >{
  console.log('Request successful',value);
}/* reason =>{throw reason} */).then(value= >{
  console.log('Request successful',value);
}).catch(reason= >{
  console.log('Request failed',reason);
})
Copy the code

Promise.all

Promse.race