Skip to content

Instantly share code, notes, and snippets.

@ashishkujoy
Last active February 4, 2025 12:48
Show Gist options
  • Save ashishkujoy/2fe40b548aedc22d14b3c7691337d4e4 to your computer and use it in GitHub Desktop.
Save ashishkujoy/2fe40b548aedc22d14b3c7691337d4e4 to your computer and use it in GitHub Desktop.
class Waada {
#state;
#value;
#error;
#onResolve;
#onReject;
constructor(completion) {
this.#state = 'PENDING';
completion((value) => this.#setResolved(value), (error) => this.#setRejected(error));
}
#setResolved(value) {
if(this.#isInPendingState()) {
this.#value = value;
this.#state = 'FULFILLED';
if(this.#onResolve) this.#onResolve(this.#value);
}
}
#setRejected(error) {
if(this.#isInPendingState()) {
this.#error = error;
this.#state = 'REJECTED';
if(this.#onReject) this.#onReject(this.#error);
}
}
#isInPendingState() {
return this.#state === 'PENDING';
}
#setOnResolve(res, rej,onResolve) {
return this.#onResolve = (value) => {
try {
res(onResolve(value))
} catch(e) {
const error = this.#onReject ? this.#onReject(e) : e;
rej(error);
}
}
}
#setOnReject(rej, onReject) {
this.#onReject = (error) => rej(onReject(error));
}
then(onResolve) {
return new Waada((res, rej) => {
this.#setOnResolve(res, rej, onResolve);
if(this.#state === 'FULFILLED') this.#onResolve(this.#value);
});
}
catch(onReject) {
return new Waada((_, rej) => {
this.#setOnReject(rej, onReject);
if(this.#state === 'REJECTED') this.#onReject(this.#error);
});
}
toString() {
return `Value: ${this.#value}, Error: ${this.#error}, State: ${this.#state}`;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment