Created
November 3, 2023 14:38
-
-
Save pmn4/cd9f75777dcb7fd9ebca34f112888075 to your computer and use it in GitHub Desktop.
Predicates for Cleanly Handling Settled Promises
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
| // Filtering | |
| export function isFulfilled<T>( | |
| value: PromiseSettledResult<T>, | |
| _index?: number, | |
| _array?: PromiseSettledResult<T>[], | |
| ): value is PromiseFulfilledResult<T> { | |
| return value.status === 'fulfilled'; | |
| } | |
| export function isRejected<T>( | |
| value: PromiseSettledResult<T>, | |
| _index?: number, | |
| _array?: PromiseSettledResult<T>[], | |
| ): value is PromiseRejectedResult { | |
| return value.status === 'rejected'; | |
| } | |
| // Mapping | |
| export function promisedValue<T>( | |
| promise: PromiseFulfilledResult<T>, | |
| _index?: number, | |
| _array?: PromiseFulfilledResult<T>[], | |
| ): T { | |
| return promise.value; | |
| } | |
| export function rejectedReason( | |
| promise: PromiseRejectedResult, | |
| _index?: number, | |
| _array?: PromiseRejectedResult[], | |
| ): PromiseRejectedResult['reason'] { | |
| return promise.reason; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use these filter and map functions to clean up your Promise handling, without having to import a bunch of types.
Go from:
To:
full example: