勉强实现了把
function MyPromise(callback){ this.status="pending", // 标记状态 this.value=undefined; // resolve函数接受的参数 this.reason=undefined; // reject 函数 this.onFulfilledCallbacks=new Set(); // 成功回调 函数集合 this.onRejectedCallbacks=new Set(); // 失败回调 函数集合 let resolve=(value)=>{ if(this.status=="pending"){ this.value=value; // 赋值 参数 this.status="fulfilled"; // 调整成功状态 this.onFulfilledCallbacks.forEach(item=>item(this.value)); // 执行函数 } } let reject=(reason)=>{ if(this.status=="pending"){ this.reason=reason; // 失败原因 this.status='rejected'; // 失败状态 this.onRejectedCallbacks.forEach(item=>item(this.reason)); // 执行失败函数 } } // 执行函数 try{ callback(resolve,reject); } catch(err){ // 捕捉失败 执行失败的函数 reject(err); } } // then 函数 MyPromise.prototype.then=function(onFulfilled,onRejected){ if(this.status=="fulfilled"){ onFulfilled(this.value); } if(this.status=="rejected"){ onRejected(this.reason); } if(this.status=="pending"){ // 返回新的promise对象 让 then 执行 链式操作 return new MyPromise((resolve,reject)=>{ this.onFulfilledCallbacks.add(onFulfilled) this.onRejectedCallbacks.add(onRejected) }) } } // catch 函数 吊起来 then函数 反复执行 MyPromise.prototype.catch=function(fn){ return this.then(null,fn); }我们调用一下 试试看
// 调用 var a=new MyPromise((resolve,reject)=>{ setTimeout(()=>{ console.log('222'); resolve('hello world'); },2000) }) a.then(res=>{ console.log(res) })不过还是有很多瑕疵的 比如 如果用户不传入一个函数要怎么处理 这些 我没做 不过实现了 基本功能 暂时算是完成了 一部分了
