Skip to content

Instantly share code, notes, and snippets.

@qoomon
Last active August 27, 2024 11:25
Show Gist options
  • Save qoomon/6315daae77bcede876a9de3604a46b7b to your computer and use it in GitHub Desktop.
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
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