Skip to content

Instantly share code, notes, and snippets.

@jjhiggz
Created August 14, 2024 21:22
Show Gist options
  • Save jjhiggz/2051df828ad93367ed0ad56cb3347ac2 to your computer and use it in GitHub Desktop.
Save jjhiggz/2051df828ad93367ed0ad56cb3347ac2 to your computer and use it in GitHub Desktop.
A syncronous typesafe promise (brought to you by chatGPT)
class SyncPromise<T> {
private value?: T;
private error?: any;
private isFulfilled: boolean = false;
private isRejected: boolean = false;
constructor(executor: () => T) {
try {
this.resolve(executor());
} catch (e) {
this.reject(e);
}
}
private resolve(value: T): void {
if (!this.isFulfilled && !this.isRejected) {
this.isFulfilled = true;
this.value = value;
}
}
private reject(reason: any): void {
if (!this.isFulfilled && !this.isRejected) {
this.isRejected = true;
this.error = reason;
}
}
public then<TResult>(onFulfilled: (value: T) => TResult): SyncPromise<TResult> {
if (this.isFulfilled && this.value !== undefined) {
try {
return new SyncPromise(() => onFulfilled(this.value!));
} catch (e) {
return new SyncPromise(() => { throw e; });
}
} else if (this.isRejected) {
return new SyncPromise(() => { throw this.error; });
}
return new SyncPromise(() => undefined as any);
}
public catch<TResult>(onRejected: (reason: any) => TResult): SyncPromise<TResult | T> {
if (this.isRejected && this.error !== undefined) {
try {
return new SyncPromise(() => onRejected(this.error));
} catch (e) {
return new SyncPromise(() => { throw e; });
}
} else if (this.isFulfilled) {
return new SyncPromise(() => this.value!);
}
return new SyncPromise(() => undefined as any);
}
public unwrap(): T {
if (this.isFulfilled) {
return this.value!;
} else if (this.isRejected) {
throw this.error;
}
throw new Error("SyncPromise is not fulfilled or rejected yet.");
}
public static resolve<T>(executor: () => T): SyncPromise<T> {
return new SyncPromise(executor);
}
}
const value = SyncPromise.resolve(() => "hello")
.then(v => v.split(""))
.then(r => r.join("hello"))
.then((result) => {
if(Math.random() > .5){
throw new Error("Failed")
}
return result
})
.catch(() => null)
.unwrap()
console.log(value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment