For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /reference/control/attemptAsync.md.

attemptAsync

Executes an asynchronous function and wraps the outcome in a Result. Awaits the returned promise — Err carries the rejection reason.

const result = await attemptAsync(() => fetchUser(id))

Usage

attemptAsync(fn)

Use attemptAsync for any Promise-returning operation that may reject: HTTP fetches, database calls, file I/O. The rejection value is normalized to an Error the same way attempt normalizes thrown values.

import { attemptAsync, isErr } from 'massaman'
// or:  import { attemptAsync, isErr } from 'massaman/control'

const user = await attemptAsync(() => fetch(`/api/users/${id}`).then((r) => r.json()))
if (isErr(user)) {
  return respond.serverError(user.error)
}
return respond.ok(user.value)

Parameters

fn() => Promise<T>required

a function returning a promise. Pass a thunk, not a promise — attemptAsync(promise) would not catch a synchronous throw inside the producing expression.

Returns

resolves to Ok<T> if the promise fulfills, Err if it rejects. Never rejects.

Promise<Result<T>>

Examples

Compose with match at a route boundary:

import { attemptAsync, match, P } from 'massaman'

const result = await attemptAsync(() => db.users.findById(id))

return match(result)
  .with(P.ok(null), () => respond.notFound())
  .with(P.ok(), ({ value }) => respond.ok(value))
  .with(P.err(), ({ error }) => respond.serverError(error))
  .exhaustive()

See also