Skip to content

Instantly share code, notes, and snippets.

@sno2
Last active June 10, 2021 10:02
Show Gist options
  • Save sno2/dbbdb5b4bfab5cf28cd5869eb91cc193 to your computer and use it in GitHub Desktop.
Save sno2/dbbdb5b4bfab5cf28cd5869eb91cc193 to your computer and use it in GitHub Desktop.
Turns any function that returns a promise into a function that returns the promise with the value and error without throwing.
function add(a: number, b: number): Promise<number> {
return Promise.resolve(a + b);
}
{
const safeAdd = goify(add);
const [val /* 7 */, err /* null */] = await safeAdd(2, 5);
}
function sub(a: number, b: number): Promise<number> {
throw Error("Ha ha!");
return Promise.resolve(a - b);
}
{
const safeSub = goify(sub);
const [val /* null */, err /* instanceof Error */] = await safeSub(6, 3); // DOES NOT THROW!
if (err !== null) {
console.log("Houston, we have a problem."); // this will log
}
}
/** @license Unlicense (Scroll to bottom for full license) */
// Included in license - by me
/** Unwraps a given `Promise` type into the value within it. */
type UnwrapPromise<T extends Promise<unknown>> = Parameters<
Exclude<Parameters<T["then"]>[0], null | undefined>
>[0];
/**
* Turns a function that returns a `Promise` into a safe, non-throwing function
* that returns a tuple that contains the value and a possible error without
* losing any typings via generics.
*/
export function goify<T extends (...args: any[]) => Promise<any>>(
func: T
): (
...args: Parameters<T>
) => Promise<[UnwrapPromise<ReturnType<T>>, null | Error]> {
return (...args: Parameters<T>) =>
new Promise((resolve, _) => {
try {
func(...args).then((val) => {
resolve([val, null]);
});
} catch (err: any) {
resolve([null, err]);
}
});
}
/**
* @license Unlicense
*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* For more information, please refer to <http://unlicense.org/>
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment