From 433ab1c2cd32575a034696a913985d8b6916a5de Mon Sep 17 00:00:00 2001 From: robonen Date: Thu, 26 Mar 2026 06:15:51 +0700 Subject: [PATCH] refactor(core/stdlib): streamline tryIt function with improved promise handling --- core/stdlib/src/async/tryIt/index.ts | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/core/stdlib/src/async/tryIt/index.ts b/core/stdlib/src/async/tryIt/index.ts index e43ab21..bec5838 100644 --- a/core/stdlib/src/async/tryIt/index.ts +++ b/core/stdlib/src/async/tryIt/index.ts @@ -4,21 +4,24 @@ export type TryItReturn = Return extends Promise ? Promise<{ error: Error; data: undefined } | { error: undefined; data: Awaited }> : { 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 * @category Async * @description Wraps promise-based code in a try/catch block without forking the control flow - * + * * @param {Function} fn - The function to try * @returns {Function} - The function that will return a tuple with the error and the result - * + * * @example * const wrappedFetch = tryIt(fetch); * const { error, data } = await wrappedFetch('https://jsonplaceholder.typicode.com/todos/1'); - * + * * @example * const { error, data } = await tryIt(fetch)('https://jsonplaceholder.typicode.com/todos/1'); - * + * * @since 0.0.3 */ export function tryIt( @@ -29,9 +32,7 @@ export function tryIt( const result = fn(...args); if (isPromise(result)) - return result - .then((value) => ({ error: undefined, data: value })) - .catch((error) => ({ error, data: undefined })) as TryItReturn; + return result.then(onResolve).catch(onReject) as TryItReturn; return { error: undefined, data: result } as TryItReturn; } catch (error) {