Last active
October 5, 2020 04:59
-
-
Save InfiniteXyy/1db30a9f27839ccab9e3fc8f2a353007 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyPromise<T> { | |
status: "PENDING" | "FULFILLED" | "REJECTED" = "PENDING"; | |
subjects: { complete: (value: T) => void }[] = []; | |
result?: T; | |
constructor(executor: (resolve: (result: MyPromise<T> | T) => void) => void) { | |
const resolver = (result: MyPromise<T> | T) => { | |
if (result instanceof MyPromise) { | |
result.then(resolver); | |
} else { | |
this.result = result; | |
this.status = "FULFILLED"; | |
this.subjects.forEach((i) => i.complete(result)); | |
} | |
}; | |
executor(resolver); | |
} | |
then<NT = T>(onFulfilled: (value: T) => NT | MyPromise<NT> | void): MyPromise<NT> { | |
const subject = { | |
subscriber: undefined, | |
complete(value: T) { | |
const nextRes = onFulfilled(value); | |
this.subscriber && this.subscriber(nextRes); | |
}, | |
}; | |
this.subjects.push(subject); | |
if (this.status === "FULFILLED") { | |
queueMicrotask(() => subject.complete(this.result)); | |
} | |
return new MyPromise((resolve) => { | |
subject.subscriber = resolve; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment