Continue with the Promise A+ specification basics introduction and continue with the Promise solution process:

Promise resolution processThe specific process is shown in the figure below.

The specific execution is as follows:

To run [[Resolve]](promise2, x), follow these steps:

  • x 与 promise2equal

var promise1 = new Promise((resolve, reject) = > {
    resolve('promise1 resolve ok~');
});

// return x
var promise2 = promise1.then((value) = > {
    //1 promsie is equal to x
    x = promise2;
    return x;
})   
Copy the code

  • xFor the Promise

For example, if x is promise1, then the returned status of promise1 determines ~

var promise1 = new Promise((resolve, reject) = > {
    resolve('promise1 resolve ok~');
});

// return x
var promise2 = promise1.then((value) = > {
    / / for promise1 x
    x = promise1;
    return x;
})  
Copy the code

  • xIs an object or function

(1), x is the object, and there is a familiarity with THEN. Assign x. Teng to THEN. If an error e is thrown when taking the value of X. Teng, then e is used as the basis to reject the promise;

If x. Chen is a function, call this with x as its scope, passing two callback functions as arguments, the first called resolvePromise and the second called rejectPromise:

  • If resolvePromise is called with the value y, run [[Resolve]](promise, y)

  • If rejectPromise is invoked with argument r, reject the promise with argument r

  • If both resolvePromise and rejectPromise are invoked, or if the same parameter is invoked more than once, the first call is preferred and the remaining calls are ignored

  • If calling the then method raises exception e:

    • ifresolvePromise 或 rejectPromiseAlready called, ignore it
    • Or otherwiseeRefusal on grounds of proofpromise
  • If then is not a function, execute the promise with an x argument


var promise1 = new Promise((resolve, reject) = > {
   resolve('promise1 resolve ok~');
  });

// return x
var promise2 = promise1.then((value) = > {
   //
   x = {
      name: 'linklogis'.age: 6.// then is a function called with 'x' as its scope 'this'
       // Pass two callback functions as arguments, the first called 'resolvePromise' and the second called 'rejectPromise' :
      then(resolvePromise, rejectPromise) {
       resolve(this.name)
      }
   };
   return x;
})  
Copy the code

Running results:

(2) If x is not an object or function, execute the promise with x as a parameter

 var promise1 = new Promise((resolve, reject) = > {
    resolve('promise1 resolve ok~');
});

// return x
var promise2 = promise1.then((value) = > {
    //
    x = {
        name: 'linklogis'
    };
    return x;
}) 
Copy the code

Running results:

The handwritten Promise will then be implemented