From 5cf134cdc40a58bd50abfd9149fada82a30821af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A9=B9=E7=A9=8E?= <5431277+zhanying189@user.noreply.gitee.com> Date: Mon, 24 May 2021 15:07:59 +0800 Subject: [PATCH] update part1/fed-e-task-01-01/code/MyPromise.js. --- part1/fed-e-task-01-01/code/MyPromise.js | 51 +++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/part1/fed-e-task-01-01/code/MyPromise.js b/part1/fed-e-task-01-01/code/MyPromise.js index 1a6b829..be90ff6 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 -- Gitee