手撕一个营养不良的Promise
function Promise(executor){ // 传进来的是个函数哦 let _this = this; this.state = PENDING; // 初始状态 this.value = undefined; // 初始化 //成功结果 this.reason = undefined; // 初始化 失败原因 this.onFulfilled = []; // 成功的回调 this.onRejected = []; // 失败的回调 function resolve(value){ if(_this.state===PENDING){ _this.state = FULFILLED _this.value = value _this.onFulfilled.forEach(f=>f(value)) } } function reject(reason){ if(_this.state === PENDING){ _this.state = REJETED _this.reason = reason _this.onRejected.forEach(f=>f(reason)) } } try{ // 为了捕获构造异常 executor(resolve,reject) }catch (e){ reject(e) } Promise.prototype.then = function (onFulfilled,onRejected){ // 定义链式调用then方法 if(_this.state === FULFILLED){ typeof onFulfilled === 'function' && onFulfilled(_this.value) } if(_this.state === REJETED){ typeof onRejected === 'function' && onRejected(_this.reason) } if(_this.state === PENDING){ typeof onFulfilled === 'function' && _this.onFulfilled.push(onFulfilled) typeof onRejected === 'function' && _this.onRejected.push(onRejected) } } }
基本上面试的话,有以上描述就差不多了