Last active
April 30, 2023 17:22
-
-
Save jasonblanchard/fbd5ebdef8ab5f1e1c16b405c9009c2c to your computer and use it in GitHub Desktop.
Revisions
-
jasonblanchard revised this gist
Apr 30, 2023 . 1 changed file with 35 additions and 5 deletions.There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -20,14 +20,44 @@ function wrap<T extends (...args: any[]) => any>(fn: T): (...args: Parameters<T> } } function wrapAsync<T extends (...args: any[]) => Promise<any>>(fn: T): (...args: Parameters<T>) => Promise<Result<ReturnType<T>>> { return async function(...args: Parameters<T>): Promise<Result<ReturnType<T>>> { try { const value = await fn(...args); return { ok: true, value, } } catch (error) { return { ok: false, error: error as Error, } } } } async function doSomethingAsync(arg: string) { return arg; } async function main() { // const result = wrap(JSON.parse)("asdf") // if (!result.ok) { // console.error("uh oh", result.error) // return; // } // console.log(result.value); const asyncResult = await wrapAsync(doSomethingAsync)('my arg') if (!asyncResult.ok) { console.error("uh oh async", result.error) return } console.log(asyncResult.value) } main() -
jasonblanchard created this gist
Apr 30, 2023 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,33 @@ type Result<T, E = Error> = | { ok: true; value: T } | { ok: false; error: E }; function wrap<T extends (...args: any[]) => any>(fn: T): (...args: Parameters<T>) => Result<ReturnType<T>> { return function(...args: Parameters<T>): Result<ReturnType<T>> { try { const value = fn(...args); return { ok: true, value, } } catch (error) { return { ok: false, error: error as Error, } } } } async function main() { const result = wrap(JSON.parse)("asdf") if (!result.ok) { console.error("uh oh", result.error) return; } console.log(result.value); } main()