Skip to content

Instantly share code, notes, and snippets.

@abdalicode
Created April 22, 2022 10:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdalicode/b3118cf4e3082dc5269921e8cdf10139 to your computer and use it in GitHub Desktop.
Save abdalicode/b3118cf4e3082dc5269921e8cdf10139 to your computer and use it in GitHub Desktop.
const CustomPromiseState = {
PENDING: "PENDING",
RESOLVED: "RESOLVED",
REJECTED: "REJECTED",
};
class CustomPromise {
constructor(fn) {
this.CustomPromiseState = CustomPromiseState.PENDING;
this.resolver = this.resolver.bind(this);
this.rejector = this.rejector.bind(this);
this.thenFns = [];
this.catchFns = [];
this.finallyFn = null;
this.resolvedData = null;
this.rejectedData = null;
fn(this.resolver, this.rejector);
}
resolver(resolvedData) {
if (this.CustomPromiseState !== CustomPromiseState.PENDING) {
return;
}
this.CustomPromiseState = CustomPromiseState.RESOLVED;
while (this.thenFns.length) {
const thenFn = this.thenFns.shift();
this.resolvedData = thenFn(this.resolvedData || resolvedData);
}
this.finallyFn && this.finallyFn(this.resolvedData || resolvedData);
}
rejector(rejectedData) {
if (this.CustomPromiseState !== CustomPromiseState.PENDING) {
return;
}
this.CustomPromiseState = CustomPromiseState.REJECTED;
while (this.catchFns.length) {
const catchFn = this.catchFns.shift();
this.rejectedData = catchFn(this.rejectedData || rejectedData);
}
this.finallyFn && this.finallyFn(this.rejectedData || rejectedData);
}
then(thenFn) {
this.thenFns.push(thenFn);
return this;
}
catch(catchFn) {
this.catchFns.push(catchFn);
return this;
}
finally(fn) {
this.finallyFn = fn;
}
}
const pr = () =>
new CustomPromise((resolve, reject) => {
setTimeout(() => {
reject("rejected");
resolve("resolved");
}, 0);
});
pr()
.then((r) => console.log(r)) //resolved
.then(() => "Success")
.then((r) => console.log(r)) // Success
.catch((e) => console.log(e)) // rejected
.catch((e) => "Error")
.catch((e) => console.log(e)) // Error
.catch(() => "catch")
.catch((e) => console.log(e)) // catch
.finally((f) => {
console.log(f); // resolved OR rejected
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment