Aller au contenu principal

fromAsyncThrowable()

const fromAsyncThrowable: <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');