Skip to content

Instantly share code, notes, and snippets.

@typeofweb
Last active August 17, 2024 09:56
Show Gist options
  • Save typeofweb/60d8c05a645865a0f24d8705b2c38607 to your computer and use it in GitHub Desktop.
Save typeofweb/60d8c05a645865a0f24d8705b2c38607 to your computer and use it in GitHub Desktop.
Turn async values and errors into tuples. https://www.npmjs.com/package/safe-try
// Also available on NPM: https://www.npmjs.com/package/safe-try
// By @typeofweb 2024
// License: MIT
type PromiseToTupleResult<T> = [Error, null] | [null, Awaited<T>];
export const try_ = async <T extends Promise<unknown>>(
promise: T,
): Promise<PromiseToTupleResult<T>> => {
try {
const result = await promise;
return [null, result];
} catch (maybeError) {
// You could change the logic here to handle errors in a more sophisticated way maybe?
const error = maybeError instanceof Error ? maybeError : new Error(String(maybeError));
return [error, null];
}
};
// usage
const [result, error] = await try_(asyncMightFail());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment