refactor(core/stdlib): streamline tryIt function with improved promise handling
This commit is contained in:
@@ -4,21 +4,24 @@ export type TryItReturn<Return> = Return extends Promise<any>
|
|||||||
? Promise<{ error: Error; data: undefined } | { error: undefined; data: Awaited<Return> }>
|
? Promise<{ error: Error; data: undefined } | { error: undefined; data: Awaited<Return> }>
|
||||||
: { error: Error; data: undefined } | { error: undefined; data: Return };
|
: { error: Error; data: undefined } | { error: undefined; data: Return };
|
||||||
|
|
||||||
|
function onResolve(data: any) { return { error: undefined, data }; }
|
||||||
|
function onReject(error: any) { return { error, data: undefined }; }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @name tryIt
|
* @name tryIt
|
||||||
* @category Async
|
* @category Async
|
||||||
* @description Wraps promise-based code in a try/catch block without forking the control flow
|
* @description Wraps promise-based code in a try/catch block without forking the control flow
|
||||||
*
|
*
|
||||||
* @param {Function} fn - The function to try
|
* @param {Function} fn - The function to try
|
||||||
* @returns {Function} - The function that will return a tuple with the error and the result
|
* @returns {Function} - The function that will return a tuple with the error and the result
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* const wrappedFetch = tryIt(fetch);
|
* const wrappedFetch = tryIt(fetch);
|
||||||
* const { error, data } = await wrappedFetch('https://jsonplaceholder.typicode.com/todos/1');
|
* const { error, data } = await wrappedFetch('https://jsonplaceholder.typicode.com/todos/1');
|
||||||
*
|
*
|
||||||
* @example
|
* @example
|
||||||
* const { error, data } = await tryIt(fetch)('https://jsonplaceholder.typicode.com/todos/1');
|
* const { error, data } = await tryIt(fetch)('https://jsonplaceholder.typicode.com/todos/1');
|
||||||
*
|
*
|
||||||
* @since 0.0.3
|
* @since 0.0.3
|
||||||
*/
|
*/
|
||||||
export function tryIt<Args extends any[], Return>(
|
export function tryIt<Args extends any[], Return>(
|
||||||
@@ -29,9 +32,7 @@ export function tryIt<Args extends any[], Return>(
|
|||||||
const result = fn(...args);
|
const result = fn(...args);
|
||||||
|
|
||||||
if (isPromise(result))
|
if (isPromise(result))
|
||||||
return result
|
return result.then(onResolve).catch(onReject) as TryItReturn<Return>;
|
||||||
.then((value) => ({ error: undefined, data: value }))
|
|
||||||
.catch((error) => ({ error, data: undefined })) as TryItReturn<Return>;
|
|
||||||
|
|
||||||
return { error: undefined, data: result } as TryItReturn<Return>;
|
return { error: undefined, data: result } as TryItReturn<Return>;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
Reference in New Issue
Block a user