SOURCE

const PENDING = 'pending';
const RESOLVE = 'resolve';
const REJECT = 'reject';
function MyPromise(fn){
  this.value = null;
  this.status = PENDING;
  this.promiseThen = {
    resolve: null,
    reject: null
  }
  this.promiseCatch = null;
  let resove = (res) => {
    if(this.status === PENDING){
      this.status = RESOLVE;
      this.value = res;
      if(typeof this.promiseThen.resolve === 'function'){
        this.promiseThen.resolve(this.value)
      }
    }
  }
  let reject = (e) => {
    if(this.status === PENDING){
      this.status = REJECT;
      this.value = res;
      if(typeof this.then.reject === 'function'){
        this.promiseThen.reject(e)
      }
      else if(typeof this.catch === 'function'){
        this.promiseCatch(e)
      }
    }
  }
  try{
    fn(resove, reject)
  }
  catch(e){
    reject(e)
  }
}
MyPromise.prototype.then = function(resolve, reject){
  if(this.status === PENDING){
    if(typeof resolve === 'function'){
      this.promiseThen.resolve = resolve
    }
    if(typeof reject === 'function'){
      this.promiseThen.reject = reject
    }
 }
  else if(this.status === RESOLVE){
    if(typeof resolve === 'function'){
      resolve(this.value)
    }
  }
  else if(this.status === REJECT){
    if(typeof reject === 'function'){
      reject()
    }
  }
}
MyPromise.prototype.catch = function(reject){
  if(this.status === PENDING){
    if(typeof reject === 'function'){
      this.promiseCatch = reject
    }
  }
  else if(this.status === REJECT){
    if(typeof reject === 'function'){
      reject()
    }
  }
}

new MyPromise((r, j) => {
  setTimeout(() => {
    r(2)
  },0)
}).then((res) => {
  console.log(res)
})













console 命令行工具 X clear

                    
>
console