promise原始写法

136 阅读1分钟
  class Kpromise{
    constructor(fn){
        this.state = 'pending'  //状态值 pending fullFilled成功 rejected失败
        this.value = undefined	//成功的返回值
        this.reason = undefined //失败的返回值
        this.fullFilledfn = []; //返回成功的函数 压入的数组
        this.rejectedfn = []; // 返回失败的函数,压入的数组
        let reslove = function(value) {
           this.state = 'fullFilled'
           this.value = value
           this.fullFilledfn.map(fn=>fn&&fn(value)) // 执行压入成功数组里的回调函数
        }
        let reject = function(reason) {
          this.state = 'rejected'
          this.reason = reason
          this.rejectedfn.map(fn=>fn&&fn(reason)) // 执行压入失败数组里的回掉函数
        }
        
        try{
          fn(reslove,reject)
        }catch(e){
          reject(e)
        }
    }
    then(reslove,reject){ // then reslove里的成功回调函数 reject失败回调函数
      return new Kpromise((res,rej)=>{
         if (this.state=="pending") { // 还在等待当中 需要把后面的then里的方法压入
           this.fullFilledfn.push(()=>{ // 在等待中的成功回调压入当前对象的成功数组里
               let h = reslove&&reslove(this.value)
               
           })
       
         } else if (this.state=="fullFilled") { // 已经执行完了并且成功状态
            let h = reslove&&reslove(this.value) // 需要先执行一下then的成功函数
            res(h||this.value)
         } else if (this.state=="fullFilled") { //  已经执行完了并且失败状态
            let y = reject&&reject(this.value)
            rej(y||this.reason)
         }
      
      })
    
    }
    catch(reject) { // 收集错误方法
           return this.then(undefined,reject)
    }
    finally(cb) { // finally 最后不管是成功还是失败 都会执行
        return this.then((val)=>{
           return Mypromise.reslove(cb()).then(()=>val)
        },(err)=>{})
    }
  }
  
  Kpromise.reslove = function(value) {
      return new Kpromise((reslove,reject)=>{
         reslove(value)
      })
  }

Kpromise是模拟promise的一些写法,主要看里面的逻辑then 里面其实就是一个新的new Kpromise, 高阶函数的完美应用,比较难得是对,传入函数的处理,已经把对象内部函数导出的函数触发,比较难理解