实现promise.then/catch和Promise.resolve

听说现在的面试官喜欢让人手写实现Promise,我也来试试,先实现最基本的功能吧,以后空了再完善别的功能~

class MyPromise{
    constructor(callback){
      console.log('进入Mypromise的构造函数里')
      this.state = 'pending';
      this.result = '';
      this.fulfillFun = null;
      this.rejectFun = null;
      let resolve = (val)=> {
        console.log('进入resolve====',val)
        if(this.state == 'pending') {
          this.state = 'fulfilled';
          this.result = val;
          if(this.fulfillFun){
//针对resolve里还嵌套了定时器等异步操作,操作执行完自动调用then里的回调
            this.fulfillFun();
            this.fulfillFun = null;
          }   
        }  
      }
      let reject = (val)=>{
        console.log('进入rejected',val)
        if(this.state == 'pending') {
          this.state = 'rejected';
          this.result = val;
          if(this.rejectFun){
            this.rejectFun(this.result);
            this.rejectFun = null;
          }
        }
      }
      try {
        callback(resolve,reject)
      }catch(e) {
        reject(e)
      } 
    }     
    then(onFulfilled, onRejected){
      if(this.state === 'pending'){
        this.fulfillFun = ()=>{
          onFulfilled(this.result)
        };
        this.rejectFun = ()=>onRejected(this.result);
      }
      else if(this.state === 'fulfilled')
        onFulfilled(this.result)
      else {
        onRejected(this.result)
      }
    }
    catch(onRejected){
      if(this.state === 'rejected')
        onRejected(this.result)
    }

    static all(arr){
        //空了再来写。。。
    }

    static resolve(onFulfilled){
      return new MyPromise((r)=>{
        r(onFulfilled)
      })
    }
  }
  
  //测试
  let mypromise = new MyPromise((r,j)=>{
    j('-------mypromise')
  })
  mypromise.then((m)=>console.log('mypromise.then:',m),
    (m)=>console.log('mypromise.catch:',m));

  let mypromise1 = new MyPromise((r,j)=>{
    setTimeout(()=>{
      j('计时器结合的mypromise1')
    },100)
  })
  mypromise1.then((m)=>console.log('******mypromise1.then:',m),
    (m)=>console.log('*******mypromise1.catch:',m));

  let myRsolvePro = MyPromise.resolve('我是要变成promise的字符串')
  myRsolvePro.then(m=>console.log('MyPromise.resolve.then:',m))

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值