Created
December 30, 2023 09:47
-
-
Save trvswgnr/0fa91f27cdef664f4d915aaaeee80c06 to your computer and use it in GitHub Desktop.
trackable promise in typescript
This file contains hidden or 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 TrackablePromise<T> extends Promise<T> { | |
private _status: PromiseStatus = "pending"; | |
private _promise: Promise<T>; | |
private _value: T | undefined; | |
constructor( | |
executor: ( | |
resolve: (value: T | PromiseLike<T>) => void, | |
reject: (reason?: any) => void, | |
) => void, | |
) { | |
super(() => {}); | |
this._promise = new Promise<T>((resolve, reject) => { | |
return executor( | |
(value) => { | |
this._status = "resolved"; | |
this._value = value as T; | |
resolve(value); | |
}, | |
(reason) => { | |
this._status = "rejected"; | |
reject(reason); | |
}, | |
); | |
}); | |
} | |
get status() { | |
return this._status; | |
} | |
get promise() { | |
return this._promise; | |
} | |
get value() { | |
return this._value; | |
} | |
then<TResult1 = T, TResult2 = never>( | |
onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, | |
onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null, | |
): Promise<TResult1 | TResult2> { | |
return this._promise.then(onfulfilled, onrejected); | |
} | |
catch<TResult = never>( | |
onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null, | |
): Promise<T | TResult> { | |
return this._promise.catch(onrejected); | |
} | |
finally(onfinally?: (() => void) | undefined | null): Promise<T> { | |
return this._promise.finally(onfinally); | |
} | |
static all<T>(iterable: Iterable<T | PromiseLike<T>>): Promise<T[]> { | |
return Promise.all(iterable); | |
} | |
static allSettled<T>( | |
iterable: Iterable<T | PromiseLike<T>>, | |
): Promise<PromiseSettledResult<T>[]> { | |
return Promise.allSettled(iterable); | |
} | |
static any<T>(iterable: Iterable<T | PromiseLike<T>>): Promise<T> { | |
return Promise.any(iterable); | |
} | |
isPending() { | |
return this._status === "pending"; | |
} | |
isResolved() { | |
return this._status === "resolved"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment