Skip to main content

fromPromise()

const fromPromise: <T, E>(promise, errorFn) => ResultAsync<T, E> = ResultAsync.fromPromise

Convenience export for ResultAsync.fromPromise.

Creates a ResultAsync from a Promise that may reject. The errorFn parameter is used to transform any rejection into an error value.


Type Parameters​

T: T​

The type of the value in the Promise

E: E​

The type of the error


Parameters​

promise: Promise<T>​

Promise that may resolve or reject

errorFn: (e) => E​

Function to transform rejections into error values


Returns: ResultAsync<T, E>​

A new ResultAsync that will resolve to Ok(value) or Err(error)


Example​

const fetchUser = (id: string) =>
fetch(`/api/users/${id}`).then(r => r.json());

const result = ResultAsync.fromPromise(
fetchUser("123"),
(error) => `Failed to fetch user: ${error}`
);

const resolved = await result;
if (resolved.isOk()) {
console.log(resolved.value); // User data
} else {
console.log(resolved.error); // Error message
}

Since​

2.0.0


Example​

import { fromPromise } from './result-async';

const result = fromPromise(
fetch('/api/data'),
error => `Fetch failed: ${error}`
);