手写promise

const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected'


const reslovePromise = (promise2,x,reslove,reject)=>{
  if(promise2===x){
    return reject(new TypeError('循环引用'))
  }
  if(typeof x ==='object' && x!=null || typeof x==='function'){
    let called = false;
    try {
      let then = x.then;
      if(typeof then==='function'){
        then.call(x,s=>{
          if(called)return;
          reslove(x)
          called = true
        },r=>{
          if(called)return;
          reject(r)
          called = true
          
         
        })
      }else{
        reslove(x)
      }
    } catch (error) {
      
    }
  }else{
    reslove(x)
  }
}
class MyPromise{
  constructor(executor){
    this.status = 'pending';
    this.value = undefined;
    this.reason = undefined;
    this.onResloveCallbacks = [];
    this.onRejectedCallbacks = [];


    const reslove = (value)=>{
      if(this.status===PENDING){

        this.value =value;
        this.status = FULFILLED;
        this.onResloveCallbacks.forEach(fn=>fn())
      }
    }
    const reject = (reason)=>{
      if(this.status===PENDING){

        this.reason = reason
        this.status = REJECTED;
        this.onRejectedCallbacks.forEach(fn=>fn())
      }
    }
    try {
      executor(reslove,reject)
    } catch (error) {
      reject(error)
    }
  }
  then(onSuccess,onError){

    const promise2 = new MyPromise((reslove,reject)=>{
      if(this.status===FULFILLED){
       setTimeout(()=>{
        try {
          let x = onSuccess(this.value)
          reslovePromise(promise2,x,reslove,reject)
        } catch (error) {
          reject(error)
        }
       })
      }else if(this.status===REJECTED){
        setTimeout(()=>{
          try {
            let x = onError(this.reason);
            reslovePromise(promise2,x,reslove,reject)
          } catch (error) {
            reject(error)
          }
         })
      }else{
        //这里是异步代码,使用发布订阅
        this.onRejectedCallbacks.push(()=>{
          setTimeout(()=>{
            try {
              let x = onSuccess(this.value)
              reslovePromise(promise2,x,reslove,reject)
            } catch (error) {
              reject(error)
            }
           })
        });
        this.onRejectedCallbacks.push(()=>{
          setTimeout(()=>{
            try {
              let x = onError(this.reason);
                reslovePromise(promise2,x,reslove,reject)
            } catch (error) {
              reject(error)
            }
           })
        })
  
      }

    }) 
    return promise2

  }

  /**
   * 
   * @param {*} val 
   * @returns
   * val如果是一个基本数据类型会包装为一个promise返回,如果是promise直接返回 
   */
  static reslove(val){
    if(val instanceof MyPromise){
      return val
    }else{
      new MyPromise((reslove)=>{
        reslove(val)
      })
    }
  }
  /***
   * val不管传递的参数是什么,最后返回的嗾使promise,状态为rejected
   */
  static reject(val){
    return new MyPromise((reslove,reject)=>{
      reject(val)
    })
  }
  /**
   * 传入一个数组,数组中可以是promise也可以是基本数据
   * 只有全部成功才能执行成功的回调
   */
  static all(arr){
    new MyPromise((reslove,reject)=>{
      let res = []
      let index = 0;
      arr.forEach(item=>{
        if(item instanceof MyPromise){
          item.then(data=>{
            
            res[i] = data
            index++;
            if(index===arr.length){
              reslove(res)
            }
          },reject)
        }else{
          res[i] = current;
          index++
          if(index===arr.length){
            reslove(res)
          }
        }
      })
    })
  }
    /**
   * 传入一个数组,数组中可以是promise也可以是基本数据
   * 谁先返回就返回谁的状态
   */
  static race(arr){
    new Promise((reslove,reject)=>{
      arr.forEach(item=>{
        if(item instanceof MyPromise){
          item.then(reslove,reject)
        }else{
          reslove(item)
        }
      })
    })
  }
   finally(cb){
    return this.then((data)=>{
      cb()
    },e=>{
      throw e;
    })
  }


}

const promise = new MyPromise((reslove,reject)=>{
  reslove('success');
  reject('error')
  console.log(666)
}).then(res=>{
  console.log(res)
},err=>{
  console.log(err)
})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值