Skip to content

Instantly share code, notes, and snippets.

@InfiniteXyy
Last active October 5, 2020 04:59
Show Gist options
  • Save InfiniteXyy/1db30a9f27839ccab9e3fc8f2a353007 to your computer and use it in GitHub Desktop.
Save InfiniteXyy/1db30a9f27839ccab9e3fc8f2a353007 to your computer and use it in GitHub Desktop.
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