Promise is a new solution for asynchronous programming introduced in ES6. Old: Old was a weak use of callback functions, as followsCopy the code

What is asynchronous programming?

  • Fs file operation
  • Database operations
  • Ajax data request
  • The timer
//1.Promise encapsulates fs to read files
let fs = require('fs');
// Encapsulate a function that reads the file using promise

function mainfs(path){
  return new Promise((resolve,reject) = >{
    fs.readFile(path,(err,data) = >{
      if(err) reject(err);
      resolve(data)
    })
  });
}

mainfs('./text.txt').then(res= >{
  console.log(res.toString(),'111');
}),res= >{
  console.log(res,'222');
};

//2.Promise encapsulates AJAX requests
  function sendAJAX(url){
    return new Promise((resolve,reject) = >{
      let xhr = new XMLHttpRequest();
      xhr.responseType = 'json';
      xhr.open('GET',url)
      xhr.send();
      xhr.onreadystatechange = function(){
        if(xhr.readyState === 4) {if(xhr.status >= 200 && xhr.status < 300){
            resolve(xhr.response)
          }else{
            reject(xhr.status)
          }
        }
      }
    });
  }
  sendAJAX('https://api.imjad.cn/cloudmusic/?type=song&id=28012031').then(value= >{
    console.log(value,'111');
  },res= >{
    console.log(res,'222');
  });

Copy the code

Advantages of Promises:

  • Support for chained calls solves the problem of callback hell, where code is constantly being pushed down (code is constantly being read, making exception handling difficult).
  • More flexibility in how you specify callbacks (bind a promise object to a callback, or even multiple functions).

Promise properties

1.PromiseStatus
Change of Promise state (PromiseStatus state is a property in a Promise instance): There are three states (pending,resolve,reject), but only two conversion processes (pending->resolve,peding-> Reject). It indicates that a Promise only has two changing states, one is pending to success and the other is pending to failure, and there will be one result in the end. In addition, the state of a Promise can only be changed once.Copy the code
2.PromiseResult
The value of the Promise object (PromiseResult holds the result of an asynchronous task): Success resolve fail RejectCopy the code
How Promise states change (there are three ways)
 let p = new Promise((resolve,reject) = >{
     // Current status pending
    // Decide ('ok') //1.
    // reject('error') //2.pending(reject) - rejected(fail)
    // throw 'failed' //3.pending(反 对) - Rejected (反 对)
  })
  console.log(p);
Copy the code
Promise the related API
// 1 Promise constructor Promise(executor){}
(1Resolve,reject =>{} (resolve,reject)1.1Resolve defines internally successful execution of a function (1.2Reject defines a function that internally fails to executePromiseInternally immediately, asynchronous operations are performed in the executor (PromiseExecute immediately once created)//2 Promise.prototype.then(onResolveed,onRejected)=>{}; (Instance object of Promise)
(1OnResolveed: Successful callback (2)onRejected: Failed callback//3 Promise.prototype.catch(onRejected)=>{}; 
(1)onRejected: Failed callback/ / for
let p = new Promise((resolve,reject) = >{
    // resolve('ok')
    reject('error')
    // throw 'failed'
  })
  // p.then(value=>{
  // console.log(value); //ok
  // },reason=>{
  // console.log(reason);
  // })
  p.catch(res= >{
    console.log(res);//error
  })
  
  
  //4 Promise.resolve(value)
  (1)value: successful data orPromiseObject;// Description: Returns a success or failure Promise object
   let p = Promise.resolve('ok11')
   console.log(p);//Promise {<fulfilled>: 'ok11'}Note:1.If the argument passed is notPromiseType, returns a successful resultPromiseObject, the result of the parameter is determinedPromiseThe result of resolve of the resolve object is notPromiseType data: string,number, Boolean,undefined.null, [] {},2.If the argument passed isPromiseObject,PromiseThe result of is determined by the result of parameterslet p = Promise.resolve(new Promise((resolve,reject) = > {
        reject('error')
        //reject('ok')
      }))
      console.log(p);//error/ok, both cases succeed or fail
      
  //5 Promise.reject(value)
  (1) Any data or onePromiseObject; The result returned is always a failurePromiseobjectlet p = Promise.reject(123)
  console.log(p);/ / Promise {< rejected > : '123'} / / not Promise types of data: string, number, Boolean, undefined, null, [], {},
  (2) Can also be aPromiseObject, but the result is rejectedPromiseType of data.let p = Promise.reject(new Promise((resolve,reject) = > {
        resolve('ok')}))console.log(p);//Promise {<rejected>: Promise}
      
   //6 Promise.all(value); Value is typically an array of Promise objects, and the return result is also a Promise object.The result returned isPromiseThe value of all successful arrays is returned if one of them failslet p1 = Promise.resolve('1111')
  let p2 = Promise.resolve('2222')
  let p3 = Promise.resolve('3333')
  let p4 = Promise.reject('4444')
  let p = Promise.all([p1,p2,p3]);
  console.log(p);//fulfilled->Array(3)
  let _p = Promise.all([p1,p2,p4]);
  console.log(_p);//rejected -> '4444'
  
  
  //7 Promise.race(value); The value is typically an array of Promise objects, and the return result is also a Promise object. The outcome is determined by the first result to complete the Promise state change
  let p1 = new Promise((resolve,reject) = >{
      setTimeout(() = >{
          resolve('1111')},1000)})let p2 = Promise.resolve('2222')
  let p3 = Promise.reject('3333')
  let p = Promise.race([p1,p2]);
  let _p = Promise.race([p1,p3]);
  console.log(p); //fulfilled -> '2222'
  console.log(_p);//rejected -> '3333'
  
Copy the code

If a Promise specifies multiple success/failure callbacks, will they all be called?

  • This is called whenever a Promise changes to the corresponding state
Let p1 = new Promise((resolve,reject)=>{// resolve('1111') reject('error')}) p1.then(value=>{ console.log(value); //1111 }) p1.then(value=>{ console.log(value); //1111 }) p1.then(value=>{ console.log(value); //1111 },reason=>{ console.log(reason); //error })Copy the code

Who comes first, changing the Promise state or specifying the callback function?

1.Are likely to1.1If the promise is a synchronous function that changes the state and then executes a callback,1.2If a promise is an asynchronous function internally, a callback is performed to change the state.Copy the code

Break the Promise chain?

  • There is one and only one way only to return a Promise object in a pending state