Skip to content

Async results and options ​

AsyncResult and AsyncOption let you chain operations before awaiting a result or option:

Getting an async value ​

typescript
import { Ok } from 'results-ts';

const asyncResult = Ok(1).mapAsync(async (n) => n + 1);
//    ^? AsyncResult<number, never>

const result = await asyncResult; // Ok(2)

mapAsync returns an async wrapper. Its chainable methods also return async wrappers.

Chaining ​

Chain methods on AsyncResult and AsyncOption as you would on their synchronous types:

typescript
import { Ok, Err } from 'results-ts';

const loadUser = async (id: number) => {
    if (id === 13) return Err({ code: 'NOT_FOUND', id } as const);
    return Ok({ id, name: 'Ada' });
};

const name = await Ok(1)
    .andThenAsync(loadUser)
    .map((user) => user.name)
    .unwrapOr('anonymous');

Methods such as AsyncResult.unwrapOr() return a Promise of the contained value or fallback. The example awaits that promise to get a string. Use AsyncResult.match() to handle each variant with a function.

Callbacks in ordinary chains do not convert thrown errors or rejected promises to Err. Those failures propagate. Return Err for recoverable failures, or see Exception adapters for an unavoidable throwing boundary.

Panics become rejections ​

Result.unwrap() and Result.expect() throw on Err. Result.unwrapErr() and Result.expectErr() throw on Ok.

The same methods on AsyncResult reject with PanicError. For recoverable failures, use AsyncResult.unwrapOr(), AsyncResult.unwrapOrElse(), or AsyncResult.match().

typescript
import { Ok, Err } from 'results-ts';

// Resolves to 42.
const value = await Ok(21)
    .mapAsync(async (n) => n * 2)
    .unwrap(); // 42

// Rejects with PanicError.
await Err('boom')
    .mapAsync(async (n) => n)
    .unwrap();
// PanicError: called `Result.unwrap()` on an `Err` value

The same applies to AsyncOption's panic methods.

Next steps ​