Skip to content

Instantly share code, notes, and snippets.

@wiledal
Last active August 22, 2023 12:13
Show Gist options
  • Save wiledal/defe10d36bc632b8bc6cd87f61c267a3 to your computer and use it in GitHub Desktop.
Save wiledal/defe10d36bc632b8bc6cd87f61c267a3 to your computer and use it in GitHub Desktop.
until.ts
/**
Value first, might be nicer
@example
const [value] = tryCatch(doSomething())
if (!value) {
// something went wrong
}
*/
const tryCatch = async <TSuccess, TError extends Error>(
promise: Promise<TSuccess>
): Promise<[result: TSuccess | null, error: TError | null]> => {
try {
return [await promise, null];
} catch (err) {
return [null, err as TError];
}
};
export async function until<TPromise extends PromiseLike<unknown>>(
promise: TPromise
): Promise<
[error: unknown | undefined, result: Awaited<TPromise> | undefined]
> {
try {
return [undefined, await promise];
} catch (err) {
return [err, undefined];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment