Last active
November 17, 2021 16:30
-
-
Save emersondemetrio/325805bf393ac0fca0dc57ea8f4eb857 to your computer and use it in GitHub Desktop.
Promise unwrapper to avoid nested try/catch blocks
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
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