import {getError, ok} from './misc'; import type {ExtendedErr, ExtendedResult, Result} from './models'; // #region Functions /** * Executes a _Promise_, catching any errors, and returns a result * * _Available as `asyncAttempt` and `attempt.async`_ * * @param promise _Promise_ to execute * @param error Error value * @returns Callback result */ export async function asyncAttempt( promise: Promise, error: E, ): Promise, E>>; /** * Executes a callback asynchronously, catching any errors, and returns a result * * _Available as `asyncAttempt` and `attempt.async`_ * * @param callback Callback to execute * @param error Error value * @returns Callback result */ export async function asyncAttempt( callback: () => Promise, error: E, ): Promise, E>>; /** * Executes a _Promise_, catching any errors, and returns a result * * _Available as `asyncAttempt` and `attempt.async`_ * * @param promise _Promise_ to execute * @returns Callback result */ export async function asyncAttempt(promise: Promise): Promise>>; /** * Executes a callback asynchronously, catching any errors, and returns a result * * _Available as `asyncAttempt` and `attempt.async`_ * * @param callback Callback to execute * @returns Callback result */ export async function asyncAttempt( callback: () => Promise, ): Promise>>; export async function asyncAttempt( value: Promise | (() => Promise), err?: E, ): Promise { try { let result = typeof value === 'function' ? value() : await value; if (result instanceof Promise) { result = await result; } return ok(result); } catch (thrown) { return getError((err ?? thrown) as E, err == null ? undefined : (thrown as Error)); } } /** * Executes a callback, catching any errors, and returns a result * * @param callback Callback to execute * @param error Error value * @returns Callback result */ export function attempt(callback: () => Value, error: E): ExtendedResult; /** * Executes a callback, catching any errors, and returns a result * * @param callback Callback to execute * @returns Callback result */ export function attempt(callback: () => Value): Result; export function attempt( callback: () => Value, err?: E, ): ExtendedErr | Result { try { const value = callback(); return ok(value); } catch (thrown) { return getError((err ?? thrown) as E, err == null ? undefined : (thrown as Error)); } } attempt.async = asyncAttempt; // #endregion