• Safely executes an async operation with error handling.

    Type Parameters

    • T

    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.

    const { data, error } = await safeAsync(() => fetchData());
    
    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 };
    }
    }