面试官:来,你给我手写个Promise!

89 阅读1分钟

` const PENDING = 'PENDING';

const RESOLVED = 'RESOLVED';

const REJECTED = 'REJECTED';

// 对于不太经常更改的变量 定于为常量

function MyPromise(fn){

//存一下this  因为在setTimeout中的resolve 调用中 resolve函数 this指向window
var that = this;
// 初始状态 
that.state = PENDING;
//接受的参数
that.value = null;

that.rejectCalbacks = [];
that.resolveCallbacks = [];

function resolve(value){
    if(that.state === PENDING){
        
        that.state = RESOLVED;
        that.value = value;
      
        that.resolveCallbacks.map( cb => cb(that.value));
    }
}
function reject(value){
    
    if(that.state === PENDING){
        
        that.state = REJECTED;
        that.value = value;

        that.rejectCalbacks.map( cb => cb(that.value));
    }
}
try{
    fn(resolve,reject);
}catch(e){
    reject(this.value);
}

}

MyPromise.prototype = {

constructor:MyPromise,
then(onFulFulled,onRejected){
    onFulFulled = typeof onFulFulled === 'function' ? onFulFulled : v => v;
    onRejected = typeof onRejected === 'function' ? onRejected : r => { 
        //直接抛出
        throw r;
      };

      if(this.state === PENDING){
          this.rejectCalbacks.push(onRejected);
          this.resolveCallbacks.push(onFulFulled);
          console.log(this.resolveCallbacks)
      }
      if(this.state === RESOLVED){
          onFulFulled(this.value);
      }
      if(this.state === REJECTED){
        onRejected(this.value);
    }
}

}

//调用 参考eventLoop 执行机制
new MyPromise((resolve,reject) => { // 异步宏任务 最后执行 setTimeout(() => { if(Math.random() > 0.1){ resolve('成功'); }else{ reject('傻哎'); } },2000) }) // Promise.then是微任务 但在这里手动实现 是一个同步任务 这里会将处理函数压入 reject 和resolve 状态数组中
.then( ok => { console.log(ok) })

` 原格式在这里,掘金的代码块有点难调