A promise is a solution for asynchronous programming introduced in ES6. Syntactically, a promise is a constructor that encapsulates asynchronous operations and allows for success and failure. Such as:

const p = new Promise(function(resolve,reject){
  setTimeout(function(){
   const data = 'promise';
   // Resove was successfully used
   resolve(data)
   // Reject when you fail
   reject(data)
  },1000)})// Call this method
p.then(
// Successful callback
function(val){},// Failed callback
function(data){})Copy the code

A promise has three states to wait for: Pendding Successful: Resolve failed: Reject When the state is successful or failed, the state cannot be changed. Call Resove when it succeeds, Reject when it fails, and promise when it fails. This is a very useful way to solve asynchronous callback hell, avoiding code that is nested all the time and maintaining it.

Promise.all ([‘ XXX ‘,’yyy’]). Then (res=>{}) The then method callback is executed when all promise methods have completed execution. This can be useful for asynchronous methods with a correlation.

Promise.race ([‘ XXX ‘,’yyy’]). Then (res =>{}) Other promise no longer raced the callback, and | | or the use of similar, when one is true is true, but they will continue to perform its own callback.

Iv. Study Time: 2021.06.16 PM

Five, the summary

Promises can be very useful when using asynchronous requests to tease out the logic and better understand the project code so that asynchronous request methods are not nested like nesting dolls.