Aller au contenu principal

safeAsyncTry()

safeAsyncTry<T>(fn): Promise<Result<T, unknown>>

Wraps an async function with try-catch error handling, returning a Promise that resolves to a Result instead of rejecting.

Uses unknown for error types to maintain maximum type safety and flexibility.


Type Parameters

T: T

The type of the value returned by the async function


Parameters

fn: () => Promise<T>

Async function to wrap with error handling


Returns: Promise<Result<T, unknown>>

A Promise that resolves to a Result


Since

1.1.0


Example

const fetchUser = async (id: string) => {
const response = await fetch(`/api/users/${id}`);
return response.json();
};

const result = await safeAsyncTry(() => fetchUser("123"));
if (result.isOk()) {
console.log(result.value); // User data
} else {
console.log(result.error); // Error details
}