Skip to content

Instantly share code, notes, and snippets.

@lubieowoce
Created April 14, 2025 11:36
Show Gist options
  • Save lubieowoce/7d2cce5913c0f609b21698e4764179ce to your computer and use it in GitHub Desktop.
Save lubieowoce/7d2cce5913c0f609b21698e4764179ce to your computer and use it in GitHub Desktop.
trackThenableState
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