fromAsyncThrowable()
constfromAsyncThrowable: <A,R,E>(fn,errorFn?) => (...args) =>ResultAsync<R,E> =ResultAsync.fromThrowable
Convenience export for ResultAsync.fromThrowable.
Maintains compatibility with Neverthrow's API while providing enhanced type safety.
Wraps an async function with try-catch error handling, creating a new function that returns a ResultAsync instead of throwing exceptions.
Uses unknown types for maximum type safety and modern TypeScript syntax.
Type Parametersโ
A: A extends unknown[]โ
The types of the function arguments
R: Rโ
The return type of the async function
E: E = unknownโ
The type of the error
Parametersโ
fn: (...args) => Promise<R>โ
Async function to wrap with error handling
errorFn?: (err) => Eโ
Optional function to transform thrown errors
Returnsโ
A new function that returns a ResultAsync instead of throwing
Exampleโ
const fetchUser = async (id: string) => {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
};
const safeFetchUser = ResultAsync.fromThrowable(
fetchUser,
(error) => `User fetch failed: ${error}`
);
const result = await safeFetchUser("123");
if (result.isOk()) {
console.log(result.value); // User data
} else {
console.log(result.error); // Error message
}
Sinceโ
2.0.0
Exampleโ
import { fromAsyncThrowable } from './result-async';
const safeFetch = fromAsyncThrowable(
fetch,
error => `Request failed: ${error}`
);
const result = await safeFetch('/api/data');