• Safely executes an async operation with error handling. Wraps an async function and returns a result object containing either successful data or an error.

    Type Parameters

    • T

      The type of data returned by the async function.

    Parameters

    • asyncFn: () => Promise<T>

      The async function to execute.

    • OptionalonError: (error: AppError) => void

      Optional callback for handling errors.

    Returns Promise<{ data: null | T; error: null | AppError }>

    An object containing either the data or the error.

    export async function safeAsync<T>(
    asyncFn: () => Promise<T>,
    onError?: (error: AppError) => void,
    ): Promise<{ data: T | null; error: AppError | null }> {
    try {
    const data = await asyncFn();
    return { data, error: null };
    } catch (error) {
    const appError = handleNetworkError(error);
    if (onError) {
    onError(appError);
    }
    return { data: null, error: appError };
    }
    }