Created
April 14, 2025 11:36
-
-
Save lubieowoce/7d2cce5913c0f609b21698e4764179ce to your computer and use it in GitHub Desktop.
trackThenableState
This file contains 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
export type Thenable<T> = | |
| PendingThenable<T> | |
| FulfilledThenable<T> | |
| RejectedThenable<T> | |
type PendingThenable<T> = Promise<T> & { status: 'pending' } | |
type FulfilledThenable<T> = Promise<T> & { status: 'fulfilled'; value: T } | |
type RejectedThenable<T> = Promise<T> & { status: 'rejected'; reason: unknown } | |
export function trackThenableState<T>(promise: Promise<T>): Thenable<T> { | |
// check if it's already instrumented. | |
const maybeThenable = promise as Thenable<T> | Promise<T> | |
if ('status' in maybeThenable && typeof maybeThenable.status === 'string') { | |
return promise as Thenable<T> | |
} | |
const pendingThenable = promise as PendingThenable<T> | |
pendingThenable.status = 'pending' | |
pendingThenable.then( | |
(value) => { | |
const fulfilledThenable = promise as FulfilledThenable<T> | |
fulfilledThenable.status = 'fulfilled' | |
fulfilledThenable.value = value | |
}, | |
(reason) => { | |
const rejectedThenable = promise as RejectedThenable<T> | |
rejectedThenable.status = 'rejected' | |
rejectedThenable.reason = reason | |
} | |
) | |
return promise as Thenable<T> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment