Promise objects are new to ES6. When you build a promise object, the callback usually has resolve and reject parameters, which indicate the information to be returned if the execution succeeds or fails, respectively:

 // Declare a Promise object
 let p = new Promise((resolve, reject) = > {
  let a = 1 + 1;
  if (a == 2) {
      resolve('success')}else {
      reject('failed')}// Use the Promise object
// then represents the callback to execute resolve
// Catch represents a callback in reject
  p.then((message) = > {
    consolve.log(message); 
  }).catch(message= >{ consolve.log(message); })})Copy the code

In addition to generating promise as a constructor, there are all and race methods under the prototype:

const a = new promise((resolve, reject) = > {
    resolve('a')})const b = new promise((resolve, reject) = > {
    resolve('b')})const c = new promise((resolve, reject) = > {
    resolve('c')})// all
Promise.all([
  a,
  b,
  c
]).then((message) = > {// Wait for results from all A, B, and C Promise objects before executing this callback
  console.log(message);// Return an array containing the a, b, c Promise object resolve
})
// race
Promise.race([
  a,
  b,
  c
]).then((message) = > {// Execute this callback when there is an execution result
  console.log(message);// Return a, b, and c promise
})
Copy the code

The above is the use of promise. Next, in order to further learn the internal use principle of promise, I will roughly imitate promise and create a prototype of myPromise:

function myPromise (fun) {
    / / state
    this.status = "pending";
    // Call back the value passed in, which can be retrieved later based on the value under the instance
    this.value = undefined;
    
    // The function executed on success
    let resolve = value= > {
        this.status = "resolved";
        this.value = value;
        let p = this.successQueue[0](value);
        for (let i = 1; i < this.successQueue.length; i++) {
            p.then(this.successQueue[i], this.failedQueue[i]); }}// The function to execute on failure
    let reject = value= > {
        this.status = "rejected";
        this.value = value;
        this.failedQueue[0](value);
    }
    
    fun(resolve, reject);
    this.successQueue = [];
    this.failedQueue = [];
}

myPromise.prototype.then = function(successFun, failedFun) {
    this.successQueue.push(successFun); // Success queue
    this.failedQueue.push(failedFun); // Failure queue
    return this; // Return the instance itself, which can be used to make chained calls to then
}

/ / use
// Pass myPromise the callback is fun
let aa = new myPromise(function(resolve, reject) {
    setTimeout(function(){
       resolve(111);  
    }, 3000);
});

let bb = new myPromise(function(resolve, reject) {
    setTimeout(function(){
       resolve(222);  
    }, 3000);
});

aa.then(() = > { / / resolve the callback
    console.log("success1");
    return bb; // Return the Promise object for the next then
}, () = > { / / reject callback
    console.log("failed1")
}).then(() = > {
    console.log("success2");
}, () = > {
    console.log("failed2")})Copy the code

Execution process of appeal code: The AA object executes the THEN method twice, pushing success1 and Success2 callbacks to the successQueue and failedQueue in the AA myPromise instance, and then executing resolve(111), The SUCCESS1 callback has been executed and the p variable in AA’s resolve will be an instance of BB myPromise returned by Success1, passing the Success2 callback into BB myPromise, SuccessQueue and failedQueue in the BB myPromise instance just push success2’s callback, then resolve(222), The SUCCESS2 callback has been executed and the p variable in AA’s resolve will be undefined because the SUCCESS2 callback does not return, and the execution is complete. Success1 and Success2 are printed together three seconds later, success1 first, success2 second, but not three seconds and then three seconds like some students think.