Last active
August 27, 2024 11:25
-
-
Save qoomon/6315daae77bcede876a9de3604a46b7b to your computer and use it in GitHub Desktop.
Revisions
-
qoomon renamed this gist
Aug 27, 2024 . 1 changed file with 5 additions and 5 deletions.There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -1,7 +1,7 @@ function resultOf<T>(fn: () => T): SafeResult<T>; function resultOf<T>(fn: () => Promise<T>): Promise<SafeResult<T>>; function resultOf<T>(promise: Promise<T>): SafeResult<T>; function resultOf<T>(input: (() => T | Promise<T>) | Promise<T>): Result<T> | Promise<Result<T>> { if (typeof input === 'function') { try { const result = input() @@ -21,6 +21,6 @@ function safe<T>(input: (() => T | Promise<T>) | Promise<T>): SafeResult<T> | Pr } } type Result<T> = { success: true, data: T, error?: never } | { success: false, error: unknown, data?: never }; -
qoomon created this gist
Aug 23, 2024 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,26 @@ function safe<T>(fn: () => T): SafeResult<T>; function safe<T>(fn: () => Promise<T>): Promise<SafeResult<T>>; function safe<T>(promise: Promise<T>): SafeResult<T>; function safe<T>(input: (() => T | Promise<T>) | Promise<T>): SafeResult<T> | Promise<SafeResult<T>> { if (typeof input === 'function') { try { const result = input() if (result instanceof Promise) { return safe(result); } return {data: result, success: true as const}; } catch (error) { return {error, success: false as const}; } } if (input instanceof Promise) { return input.then( (data) => ({data, success: true as const}), (error) => ({error, success: false as const}) ); } } type SafeResult<T> = { success: true, data: T, error?: never } | { success: false, error: unknown, data?: never };