diff --git a/part1/fed-e-task-01-01/code/MyPromise.js b/part1/fed-e-task-01-01/code/MyPromise.js index 1a6b829acd45656f84b2f476ea9ae1f26ca8dd5a..be90ff69aa0daccd6577bfcbecd42015709ddc45 100644 --- a/part1/fed-e-task-01-01/code/MyPromise.js +++ b/part1/fed-e-task-01-01/code/MyPromise.js @@ -1,3 +1,52 @@ /* 尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理. -*/ \ No newline at end of file +*/ +const PENDING='pending'; +const RESOLVED='resolved'; +const REJECTED='rejected';//三种状态 + +function MyPromise(fn){//接收一个函数,会立即执行 + const that=this; + this.state=PENDING;//promise的初始状态 + this.value=null;//value用于保存resolve 或reject中传入的值 + + that.resolvedCallbacks=[];//用于保存then中的回调 + that.rejectedCallbacks=[]; + + function resolve(value){ + if(that.state===PENDING){//判断当前状态是否pending + that.state=RESOLVED; + that.value=value; + that.resolvedCallbacks.map(cb=>cb(that.value))//遍历回调数组并且执行 + } + } + function reject(value){ + if(that.state===PENDING){ + that.state=REJECTED; + that.value=value; + that.rejectedCallbacks.map(cb=>cb(that.value)) + } + } + try{ + fn(resolve,reject) + }catch(e){ + reject(e) + } +} +MyPromise.prototype.then=function(onFullfilled,onRejected){ + const that=this; + + onFullfilled=typeof onFullfilled === 'function' ? onFullfilled:v=>v + onRejected=typeof onRejected === 'function' ? onRejected:e=>throw e + + if(this.state===PENDING){ + this.resolvedCallbacks.push(onFullfilled) + this.rejectedCallbacks.push(onRejected) + } + if(this.state===PENDING){ + onFullfilled(that.value) + } + if(this.state===REJECTED){ + onRejected(that.value) + } +} \ No newline at end of file