Skip to content

Instantly share code, notes, and snippets.

@emersondemetrio
Last active November 17, 2021 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emersondemetrio/325805bf393ac0fca0dc57ea8f4eb857 to your computer and use it in GitHub Desktop.
Save emersondemetrio/325805bf393ac0fca0dc57ea8f4eb857 to your computer and use it in GitHub Desktop.
Promise unwrapper to avoid nested try/catch blocks
export const isAFunction = (e: unknown) => e && typeof e === "function";
export interface GenericObject {
[key: string]: unknown;
}
export type ExecutedPromiseResponse<R> = [
data: R | null,
error: GenericObject | null
];
export const executePromise = async <R>(
promiseFn: () => Promise<R>,
finallyFn?: () => void
): Promise<ExecutedPromiseResponse<R>> => {
try {
const data = await promiseFn();
return [data, null];
} catch (error) {
return [null, error];
} finally {
if (finallyFn && isAFunction(finallyFn)) {
finallyFn();
}
}
};
// Usage:
const test = async () => {
const requestSomething = () =>
new Promise((resolve) => resolve("Hey friend!"));
const [result, error] = await executePromise(requestSomething);
if (!error) {
// :) happiness
}
};
test();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment