API Reference / @evolu/common / Result / tryAsync

Function: tryAsync()

function tryAsync<T, E>(promiseFn, mapError): Promise<Result<T, E>>;

Defined in: packages/common/src/Result.ts:444

Wraps async functions or any operation returning a promise, returning a Result.

The tryAsync function provides a way to handle asynchronous code safely by catching any rejected promises and mapping errors to a custom type. If the promise resolves, it returns an Ok result. If the promise rejects, it maps the error and returns an Err result.

Example

interface FetchError {
  readonly type: "FetchError";
  readonly message: string;
}

const tryFetch = async (
  url: string,
): Promise<Result<unknown, FetchError>> =>
  tryAsync(
    async () => {
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`Request failed with status ${response.status}`);
      }
      return response.json();
    },
    (error) => ({
      type: "FetchError",
      message: String(error),
    }),
  );

const result = await tryFetch(
  "https://jsonplaceholder.typicode.com/posts/1",
);
if (result.ok) {
  console.log("Data:", result.value);
} else {
  console.error("Error:", result.error);
}

Type Parameters

Type Parameter
T
E

Parameters

ParameterType
promiseFn() => Promise<T>
mapError(error) => E

Returns

Promise<Result<T, E>>

Was this page helpful?