Created
May 9, 2025 17:15
-
-
Save javascripto/fc398a6e8eb5dd317d58396230fd3fdb to your computer and use it in GitHub Desktop.
await tryCatch
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
| type Success<T> = [T, null]; | |
| type Failure<E=Error> = [null, E]; | |
| type Result<T, E> = Success<T> | Failure<E>; | |
| /** | |
| * A utility function that wraps a promise and returns a tuple. | |
| * The first element of the tuple is the resolved value or null, | |
| * and the second element is the error or null. | |
| * | |
| * @param promise - The promise to wrap. | |
| * @returns A tuple where the first element is the resolved value or null, | |
| * and the second element is the error or null. | |
| * @example | |
| * const [result, error] = await tryCatch(fetchData()); | |
| * if (error) return console.error('Error fetching data:', error); | |
| * console.log('Fetched data:', result); | |
| * @template T - The type of the resolved value. | |
| * @template E - The type of the error. | |
| */ | |
| export async function tryCatch<T, E = Error>( | |
| promise: Promise<T>, | |
| ): Promise<Result<T, E>> { | |
| try { | |
| const result = await promise; | |
| return [result, null]; | |
| } catch (error) { | |
| return [null, error]; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment