Skip to main content

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
}