method AsyncResult.try
AsyncResult.try<T>(
fn: () => Promise<T>,
context?: Record<string, unknown>
): AsyncResult<T, UnexpectedError>

Wraps an async function that might throw into an AsyncResult.

Catches any exceptions and wraps them in UnexpectedError.

Examples

Example 1

const user = AsyncResult.try(async () => {
  const response = await fetch("/api/user");
  return await response.json();
});

const value = await user.take();
if (isErr(value)) {
  console.error("Fetch failed:", value.error);
  return;
}
console.log(value); // user object

Type Parameters

The type of the return value

Parameters

fn: () => Promise<T>

Async function that might throw

optional
context: Record<string, unknown>

Optional context to add to the error

Return Type

AsyncResult with the return value or UnexpectedError

Usage

import { AsyncResult } from "result/mod.ts";