> For AI agents: the complete documentation index is available at https://massaman.dev/llms.txt, the full documentation bundle is available at https://massaman.dev/llms-full.txt.

# attemptAsync

Executes an asynchronous function and wraps the outcome in a [`Result`](https://massaman.dev/concepts/result.md). Awaits the returned promise — `Err` carries the rejection reason.

```typescript
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.

```typescript
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.

```typescript
Promise<Result<T>>
```

## Examples

Compose with `match` at a route boundary:

```typescript
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

- [`attempt`](https://massaman.dev/reference/control/attempt.md) — synchronous variant
- [`P.ok`](https://massaman.dev/reference/match/P.md#pok) / [`P.err`](https://massaman.dev/reference/match/P.md#perr) — patterns for `match`
- [Result & Errors concept guide](https://massaman.dev/concepts/result.md)
