Open History to see the last commit
1/**
2 * Thenable types which matches React's types for promises
3 *
4 * React seemingly uses `.status`, `.value` and `.reason` properties on a promises to optimistically unwrap data from promises
5 *
6 * @see https://github.com/facebook/react/blob/main/packages/shared/ReactTypes.js#L112-L138
7 * @see https://github.com/facebook/react/blob/4f604941569d2e8947ce1460a0b2997e835f37b9/packages/react-debug-tools/src/ReactDebugHooks.js#L224-L227
8 */
9β
10interface Fulfilled<T> {
11 status: 'fulfilled'
12 value: T
13}
14interface Rejected {
15 status: 'rejected'
16 reason: unknown
17}
18interface Pending<T> {
19 status: 'pending'
20β
21 /**
22 * Resolve the promise with a value.
23 * Will remove the `resolve` and `reject` properties from the promise.
24 */
25 resolve: (value: T) => void
26 /**
27 * Reject the promise with a reason.
28 * Will remove the `resolve` and `reject` properties from the promise.
29 */
30 reject: (reason: unknown) => void
31}
32β
33export type FulfilledThenable<T> = Promise<T> & Fulfilled<T>
34export type RejectedThenable<T> = Promise<T> & Rejected
35export type PendingThenable<T> = Promise<T> & Pending<T>
36β
37export type Thenable<T> =
38 | FulfilledThenable<T>
39 | RejectedThenable<T>
40 | PendingThenable<T>
41β
42export function pendingThenable<T>(): PendingThenable<T> {
43 let resolve: Pending<T>['resolve']
44 let reject: Pending<T>['reject']
45 // this could use `Promise.withResolvers()` in the future
46 const thenable = new Promise((_resolve, _reject) => {
47 resolve = _resolve
48 reject = _reject
49 }) as PendingThenable<T>
50β
51 thenable.status = 'pending'
52 thenable.catch(() => {
53 // prevent unhandled rejection errors
54 })
55β
56 function finalize(data: Fulfilled<T> | Rejected) {
57 Object.assign(thenable, data)
58β
59 // clear pending props props to avoid calling them twice
60 delete (thenable as Partial<PendingThenable<T>>).resolve
61 delete (thenable as Partial<PendingThenable<T>>).reject
62 }
63β
64 thenable.resolve = (value) => {
65 finalize({
66 status: 'fulfilled',
67 value,
68 })
69β
70 resolve(value)
71 }
72 thenable.reject = (reason) => {
73 finalize({
74 status: 'rejected',
75 reason,
76 })
77β
78 reject(reason)
79 }
80β
81 return thenable
82}