let myPromise = function(fn) {
  let _self = this;
  this.state = 'pending'; //myPromise initializes state this.result = null; // This. Reason = null; this.resolveHandler = null; this.rejectHandler = null; // call the method equivalent to your resolve('1')
  this.resolved = val => {
    _self.state = 'resolved'; _self. Result = val; // The success value is savedif (typeof _self.resolveHandler === 'function') { _self.resolveHandler(val); / / executionthenSuccess function}}; // The asynchronous operation succeeds with a method equivalent to reject('1')
  this.rejected = val => {
    _self.state = 'rejected';
    _self.reason = val;
    if (typeof _self.rejectHandler === 'function') { _self.rejectHandler(val); / / executionthen}}; this._promise = {}; this._promise._p = _self; this._promise.then = (resolveHandler, rejectHandler) => { switch (this.state) {case 'pending'_self.resolveHandler = typeof resolveHandler ==='function' ? resolveHandler : null;
        _self.rejectHandler =
          typeof rejectHandler === 'function' ? rejectHandler : null;
        break;
      case 'resolved':
        typeof resolvedHandler === 'function' && resolvedHandler(_self.result);
        break;
      case 'rejected':
        typeof rejectedHandler === 'function'&& rejectedHandler(_self.reason); }}; / / perform new promise in turn have to function fn (enclosing resolved, enclosing the rejected)return this._promise
};

new myPromise(function(resolve, reject) {
  setTimeout(function(){
    resolve(11)
  },1000)
}).then(function(val) {
  console.log(val)
}, function() {});
 
Copy the code