Last active
August 27, 2024 11:25
-
-
Save qoomon/6315daae77bcede876a9de3604a46b7b to your computer and use it in GitHub Desktop.
Run functions or await promises in a safe way by return a result object
This file contains 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
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() | |
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 Result<T> = | |
{ success: true, data: T, error?: never } | | |
{ success: false, error: unknown, data?: never }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment