> [Agent navigation index](/llms.txt)

# Compose asynchronous typed results

Consume Brix's awaitable `ResultPromise`, adapt application promises at their boundary, and compose typed asynchronous outcomes fluently.

## Consume ResultPromise

Asynchronous Brix APIs use `ResultPromise<T, E>`. Expected failures resolve to `Err`; unexpected Promise failures still reject.

If `Result`, `Ok`, and `Err` are new to you, start with [synchronous results](/docs/results-synchronous.md).
The examples use `Booking` and `BookingNotFoundError` from that guide and the `loadBooking` adapter
defined below.

Await it when you need branch properties:

```ts
const result = await loadBooking(bookingId);

if (result.isErr()) return { error: result.error._tag };
return result.value;

```

Or chain directly and await a terminal method:

```ts
const reference = await loadBooking(bookingId)
  .map((booking) => booking.reference)
  .tapError((error) => console.warn("Booking lookup failed", { tag: error._tag }))
  .unwrapOr("Unavailable");

```

`andThen` accepts a callback returning a synchronous `Result`. `andThenAsync` accepts `Promise<Result>`, including another `ResultPromise`:

```ts
const receipt = await loadBooking(bookingId)
  .andThenAsync((booking) => loadReceipt(booking.id))
  .unwrap();

```

Here `loadReceipt` is an application operation returning `ResultPromise<Receipt, ReceiptError>`.
The resulting error type is the union of errors from both operations. `.unwrap()` intentionally
terminates this operation on failure; use `match` when the caller should display a recoverable error.

## Adapt an application promise

Wrap an application-owned `Promise<Result<T, E>>` once at its API boundary:

```ts
import { Result, resultPromise, type ResultPromise } from "brix/result";

function loadBooking(id: string): ResultPromise<Booking, BookingNotFoundError> {
  return resultPromise(
    repository
      .find(id)
      .then((booking) =>
        booking ? Result.ok(booking) : Result.err(new BookingNotFoundError({ bookingId: id })),
      ),
  );
}

```

`resultPromise` decorates the native promise in place with non-enumerable methods and is idempotent. It does not turn a rejected promise into an `Err`; catch and model only failures your application deliberately classifies as expected.

Return the decorated promise directly. Marking the wrapper `async` makes it return an ordinary
Promise and loses the fluent methods, even though the resolved `Result` is the same.

When the underlying operation throws or rejects instead of returning a `Result`, convert it with
`Result.tryPromise` and decorate the outcome:

```ts
import { Result, TaggedError, resultPromise, type ResultPromise } from "brix/result";

class BookingUnavailableError extends TaggedError("BookingUnavailableError")<{ cause: unknown }> {}

function loadBookingFromApi(id: string): ResultPromise<Booking, BookingUnavailableError> {
  return resultPromise(
    Result.tryPromise({
      try: () => bookingApi.fetch(id),
      catch: (cause) => new BookingUnavailableError({ cause }),
    }),
  );
}

```

Here `bookingApi.fetch` is an application function returning `Promise<Booking>`.

## Choose the next operation

- Use `map` for a plain success-value transformation and `mapError` to change the error shape.
- Use `andThen` or `andThenAsync` when the next step can return another expected failure.
- Use `tryRecover` or `tryRecoverAsync` when an error has an alternate Result-producing path.
- Use `tap`, `tapError`, or `tapBoth` to observe a branch without replacing its value; their `Async`
  variants wait for asynchronous observation.
- Finish with `match` to handle both branches, `unwrapOr` for a meaningful default, or `unwrap` when
  failure should terminate the operation. `unwrap` rejects with a `Panic` whose `cause` is the error.

For example, a UI can turn both outcomes into a message without throwing:

```ts
const message = await loadBooking(bookingId).match({
  ok: (booking) => `Booking ${booking.reference}`,
  err: () => "This booking is no longer available.",
});

```

Recovery replaces the original error type while preserving either original or recovered success. Async callbacks are awaited before the chain proceeds. Calling native `.then()`, `.catch()`, or `.finally()` deliberately returns an ordinary Promise and leaves the fluent Result API.

Terminal methods flatten promise-valued outputs just like native promises. An async `match` callback, a promise-valued success passed to `unwrap`, or a promise fallback passed to `unwrapOr` resolves to its awaited value.

## Test both branches

```ts
import { expect, it } from "brix/test";

it("reports a missing booking", async () => {
  const result = await loadBooking("missing");
  expect(result.isErr()).toBe(true);
  if (result.isErr()) {
    expect(result.error).toMatchObject({ bookingId: "missing" });
  }
});

```

Arrange the repository fixture to return no booking for `"missing"`. Add a successful lookup and
assert its reference as well. Separately test rejected repository promises if your adapter is meant
to preserve unexpected failures; an `Err` assertion alone does not cover that path.

For HTTP request results and retries, continue with [API routes](/docs/api-routes.md). For provider-specific result unions, see the [Contentful guide](/docs/contentful.md), [testing](/docs/testing.md), and [API reference](/docs/api-reference.md).
