From afc0c3b23b19d8f082254c3f25e394d6a2cffeae Mon Sep 17 00:00:00 2001 From: goose Date: Sat, 27 Aug 2022 11:21:13 +0800 Subject: [PATCH] feat: basic promise --- index.js | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/index.js b/index.js index 59d6c84..c945c91 100644 --- a/index.js +++ b/index.js @@ -1,21 +1,31 @@ +const Status = { + PENDING: 'pending', + FULFILLED: 'fulfilled', + REJECTED: 'rejected' +} + function myPromise(constructor) { let self = this; - self.status = "pending" //定义状态改变前的初始状态 + self.status = Status.PENDING //定义状态改变前的初始状态 self.value = undefined;//定义状态为resolved的时候的状态 self.reason = undefined;//定义状态为rejected的时候的状态 function resolve(value) { - - // TODO resolve如何改变状态及返回结果 + if (self.status === Status.PENDING) { + self.status = Status.FULFILLED + self.value = value + } } function reject(reason) { - - // TODO reject如何改变状态及返回结果 + if (self.status === Status.PENDING) { + self.status = Status.REJECTED + self.reason = reason + } } @@ -34,8 +44,12 @@ function myPromise(constructor) { } myPromise.prototype.then = function (onFullfilled, onRejected) { + if (this.status === Status.FULFILLED) { + onFullfilled?.(this.value) + } else if (this.status === Status.REJECTED) { + onRejected?.(this.reason) + } - //TODO then如何实现 } module.exports = myPromise