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 /guide/how-to/writing-async-pipelines.md.

How to mix sync and async Options

To build a pipeline that calls both synchronous and asynchronous code, keep one rule: write every step the same way, and await the result once at the end. Every byenull function accepts an Option, a Promise of an Option, or returns one, so a single async step makes the whole pipeline asynchronous and nothing else in your code changes.

Call an async API inside a pipeline

To bring an asynchronous operation into a pipeline, wrap it with fn and chain it with andThen. The step after it receives the resolved value:

import { 
import Option
Option
} from "byenull";
type
type User = {
    id: string;
    name: string;
}
User
= {
id: string
id
: string;
name: string
name
: string };
const
const users: User[]
users
:
type User = {
    id: string;
    name: string;
}
User
[] = [{
id: string
id
: "u123",
name: string
name
: "Alice" }];
const
const findUser: (id: string, users: User[]) => Option.Option<User>
findUser
=
import Option
Option
.
function fn<(id: string, users: User[]) => User | undefined>(fn: (id: string, users: User[]) => User | undefined): (id: string, users: User[]) => Option.Option<User> (+1 overload)

Wraps a function and returns a new function that returns an Option or OptionAsync .

Nullish values and Promise rejections produce None ; synchronous throws are not captured.

@typeParamF - The function type to wrap.@returnsA new function that returns an Option or OptionAsync.@example

Synchronous Function

import { Option } from 'byenull';

type User = { id: string; name: string };

const findUser = Option.fn((id: string, users: User[]) =>
users.find((user) => user.id === id),
);

findUser('u1', [{ id: 'u1', name: 'Alice' }]);
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@example

Asynchronous Function

import { Option } from 'byenull';

type User = { id: string; name: string };

const fetchUser = Option.fn(async (id: string) => {
const response = await fetch(`/api/users/${id}`);
return response.json() as Promise<User>;
});

await fetchUser('u1');
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@seemaybe - For wrapping a thunk that takes no parameters.@categoryCreators
fn
((
id: string
id
: string,
users: User[]
users
:
type User = {
    id: string;
    name: string;
}
User
[]) =>
users: User[]
users
.
Array<User>.find(predicate: (value: User, index: number, obj: User[]) => unknown, thisArg?: any): User | undefined (+1 overload)

Returns the value of the first element in the array where predicate is true, and undefined otherwise.

@parampredicate find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.@paramthisArg If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.
find
((
user: User
user
) =>
user: User
user
.
id: string
id
===
id: string
id
));
const
const fetchAvatar: (user: User) => Option.OptionAsync<{
    url: string;
}>
fetchAvatar
=
import Option
Option
.
function fn<(user: User) => Promise<{
    url: string;
} | null>>(fn: (user: User) => Promise<{
    url: string;
} | null>): (user: User) => Option.OptionAsync<{
    url: string;
}> (+1 overload)

Wraps a function and returns a new function that returns an Option or OptionAsync .

Nullish values and Promise rejections produce None ; synchronous throws are not captured.

@typeParamF - The function type to wrap.@returnsA new function that returns an Option or OptionAsync.@example

Synchronous Function

import { Option } from 'byenull';

type User = { id: string; name: string };

const findUser = Option.fn((id: string, users: User[]) =>
users.find((user) => user.id === id),
);

findUser('u1', [{ id: 'u1', name: 'Alice' }]);
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@example

Asynchronous Function

import { Option } from 'byenull';

type User = { id: string; name: string };

const fetchUser = Option.fn(async (id: string) => {
const response = await fetch(`/api/users/${id}`);
return response.json() as Promise<User>;
});

await fetchUser('u1');
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@seemaybe - For wrapping a thunk that takes no parameters.@categoryCreators
fn
(async (
user: User
user
:
type User = {
    id: string;
    name: string;
}
User
) => {
const
const response: Response
response
= await
function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>
fetch
(`/api/avatars/${
user: User
user
.
id: string
id
}`);
return
const response: Response
response
.
Body.json(): Promise<any>
json
() as
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<{
url: string
url
: string } | null>;
}); const
const avatarUrl: Option.Option<string>
avatarUrl
= await
import Option
Option
.
function pipe<Option.Option<string>, Option.Option<User>, Option.OptionAsync<{
    url: string;
}>, Option.OptionAsync<string>>(a: Option.Option<string>, ab: (a: Option.Option<string>) => Option.Option<User>, bc: (b: Option.Option<User>) => Option.OptionAsync<{
    url: string;
}>, cd: (c: Option.OptionAsync<{
    url: string;
}>) => Option.OptionAsync<string>): Option.OptionAsync<string> (+25 overloads)

Applies a sequence of functions to a value, from left to right.

This utility enables function composition in a left-to-right manner. It supports up to 25 chained functions from A through Z.

@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@example
import { Option } from 'byenull';

const result = Option.pipe(
  2,
  x => x + 1,
  x => x * 3,
  x => `Result: ${x}`
);
// Result: 9
@categoryUtilities
pipe
(
import Option
Option
.
function some<string>(value: string): Option.Option<string>

Creates a Some from a given value. Passing null or undefined returns None instead.

@typeParamT - The type of the value to wrap.@returnsA Some containing the value, or None if the value is nullish.@example
import { Option } from 'byenull';

const some = Option.some(42);
// { type: 'Some', value: 42 }

const none = Option.some(null);
// { type: 'None' }
@categoryCreators
some
("u123"),
import Option
Option
.
function andThen<(id: any) => Option.Option<User>>(fn: (id: any) => Option.Option<User>): <O1>(option: O1) => Option.OptionFor<Option.Option<User> | O1, User> (+1 overload)

Chains the next computation using the value of an Option or OptionAsync . If the input is a None , it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.

@typeParamF - The function type to chain.@example

Some Case

import { Option } from 'byenull';

const option = Option.pipe(
Option.some(2),
Option.andThen((x) => Option.some(x * 2)),
);
// { type: 'Some', value: 4 }
@example

None Case (fn is never called)

import { Option } from 'byenull';

const option = Option.pipe(
Option.none(),
Option.andThen((x: number) => Option.some(x * 2)),
);
// { type: 'None' }
@example

Asynchronous Case

import { Option } from 'byenull';

type User = { id: string; name: string };

const fetchUser = Option.fn(async (id: string) =>
fetch(`/api/users/${id}`).then((response) => response.json() as Promise<User>),
);

const option = await Option.pipe(
Option.some('u123'),
Option.andThen(fetchUser),
);
// { type: 'Some', value: User }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
andThen
((
id: any
id
) =>
const findUser: (id: string, users: User[]) => Option.Option<User>
findUser
(
id: any
id
,
const users: User[]
users
)), // sync
import Option
Option
.
function andThen<(user: User) => Option.OptionAsync<{
    url: string;
}>>(fn: (user: User) => Option.OptionAsync<{
    url: string;
}>): <O1>(option: O1) => Option.OptionFor<Option.OptionAsync<{
    url: string;
}> | O1, {
    url: string;
}> (+1 overload)

Chains the next computation using the value of an Option or OptionAsync . If the input is a None , it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.

@typeParamF - The function type to chain.@example

Some Case

import { Option } from 'byenull';

const option = Option.pipe(
Option.some(2),
Option.andThen((x) => Option.some(x * 2)),
);
// { type: 'Some', value: 4 }
@example

None Case (fn is never called)

import { Option } from 'byenull';

const option = Option.pipe(
Option.none(),
Option.andThen((x: number) => Option.some(x * 2)),
);
// { type: 'None' }
@example

Asynchronous Case

import { Option } from 'byenull';

type User = { id: string; name: string };

const fetchUser = Option.fn(async (id: string) =>
fetch(`/api/users/${id}`).then((response) => response.json() as Promise<User>),
);

const option = await Option.pipe(
Option.some('u123'),
Option.andThen(fetchUser),
);
// { type: 'Some', value: User }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
andThen
(
const fetchAvatar: (user: User) => Option.OptionAsync<{
    url: string;
}>
fetchAvatar
), // async
import Option
Option
.
function map<Option.OptionAsync<{
    url: string;
}>, string>(fn: (a: {
    url: string;
}) => string): (option: Option.OptionAsync<{
    url: string;
}>) => Option.OptionAsync<string> (+1 overload)

Applies a transformation function to the value of an Option or OptionAsync . If the input is a None , it is returned unchanged.

@typeParamO - The input Option or OptionAsync.@typeParamU - The transformed value type.@example

Some Case

import { Option } from 'byenull';

const option = Option.pipe(
Option.some(2),
Option.map((x) => x * 10),
);
// { type: 'Some', value: 20 }
@example

None Case (unchanged)

import { Option } from 'byenull';

const option = Option.pipe(
Option.none(),
Option.map((x: number) => x * 10),
);
// { type: 'None' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
map
((
avatar: {
    url: string;
}
avatar
) =>
avatar: {
    url: string;
}
avatar
.
url: string
url
),
); // Option<string>

Start a pipeline from a Promise

If your input is already a Promise<Option<T>>, for example an OptionAsync produced elsewhere, pass it as the first argument of pipe and await the result:

import { 
import Option
Option
} from "byenull";
type
type Config = {
    host: string;
}
Config
= {
host: string
host
: string };
const
const loadConfig: () => Promise<Option.Option<Config>>
loadConfig
= async ():
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<
import Option
Option
.
type Option<T> = Option.Some<T> | Option.None

A union type representing either a Some or a None .

@typeParamT - The type of the Some value.@example
import { Option } from 'byenull';

const doSomething = (): Option.Option<number> => {
  return Math.random() > 0.5
    ? Option.some(10)
    : Option.none();
};
@categoryCore Types
Option
<
type Config = {
    host: string;
}
Config
>> => {
const
const response: Response
response
= await
function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>
fetch
("/api/config");
return
import Option
Option
.
function some<Config | null>(value: Config | null): Option.Option<Config>

Creates a Some from a given value. Passing null or undefined returns None instead.

@typeParamT - The type of the value to wrap.@returnsA Some containing the value, or None if the value is nullish.@example
import { Option } from 'byenull';

const some = Option.some(42);
// { type: 'Some', value: 42 }

const none = Option.some(null);
// { type: 'None' }
@categoryCreators
some
((await
const response: Response
response
.
Body.json(): Promise<any>
json
()) as
type Config = {
    host: string;
}
Config
| null);
}; const
const config: Option.Option<string>
config
= await
import Option
Option
.
function pipe<Promise<Option.Option<Config>>, Option.OptionAsync<string>>(a: Promise<Option.Option<Config>>, ab: (a: Promise<Option.Option<Config>>) => Option.OptionAsync<string>): Option.OptionAsync<string> (+25 overloads)

Applies a sequence of functions to a value, from left to right.

This utility enables function composition in a left-to-right manner. It supports up to 25 chained functions from A through Z.

@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@example
import { Option } from 'byenull';

const result = Option.pipe(
  2,
  x => x + 1,
  x => x * 3,
  x => `Result: ${x}`
);
// Result: 9
@categoryUtilities
pipe
(
const loadConfig: () => Promise<Option.Option<Config>>
loadConfig
(), // OptionAsync<Config>
import Option
Option
.
function map<Promise<Option.Option<Config>>, string>(fn: (a: Config) => string): (option: Promise<Option.Option<Config>>) => Option.OptionAsync<string> (+1 overload)

Applies a transformation function to the value of an Option or OptionAsync . If the input is a None , it is returned unchanged.

@typeParamO - The input Option or OptionAsync.@typeParamU - The transformed value type.@example

Some Case

import { Option } from 'byenull';

const option = Option.pipe(
Option.some(2),
Option.map((x) => x * 10),
);
// { type: 'Some', value: 20 }
@example

None Case (unchanged)

import { Option } from 'byenull';

const option = Option.pipe(
Option.none(),
Option.map((x: number) => x * 10),
);
// { type: 'None' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
map
((
config: Config
config
) =>
config: Config
config
.
host: string
host
),
); // Option<string>

Recover asynchronously

To provide a fallback that is itself asynchronous, give orElse a thunk that returns an OptionAsync:

import { 
import Option
Option
} from "byenull";
declare function
function readThrough(key: string): Promise<string | null>
readThrough
(
key: string
key
: string):
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<string | null>;
declare function
function warmUp(): Promise<string | null>
warmUp
():
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<string | null>;
const
const value: string
value
= await
import Option
Option
.
function pipe<Option.Option<string>, Option.OptionAsync<string>, Option.OptionAsync<string>, Promise<string>>(a: Option.Option<string>, ab: (a: Option.Option<string>) => Option.OptionAsync<string>, bc: (b: Option.OptionAsync<string>) => Option.OptionAsync<string>, cd: (c: Option.OptionAsync<string>) => Promise<string>): Promise<string> (+25 overloads)

Applies a sequence of functions to a value, from left to right.

This utility enables function composition in a left-to-right manner. It supports up to 25 chained functions from A through Z.

@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@example
import { Option } from 'byenull';

const result = Option.pipe(
  2,
  x => x + 1,
  x => x * 3,
  x => `Result: ${x}`
);
// Result: 9
@categoryUtilities
pipe
(
import Option
Option
.
function some<string>(value: string): Option.Option<string>

Creates a Some from a given value. Passing null or undefined returns None instead.

@typeParamT - The type of the value to wrap.@returnsA Some containing the value, or None if the value is nullish.@example
import { Option } from 'byenull';

const some = Option.some(42);
// { type: 'Some', value: 42 }

const none = Option.some(null);
// { type: 'None' }
@categoryCreators
some
("session-key"),
import Option
Option
.
function andThen<(key: any) => Option.OptionAsync<string>>(fn: (key: any) => Option.OptionAsync<string>): <O1>(option: O1) => Option.OptionFor<Option.OptionAsync<string> | O1, string> (+1 overload)

Chains the next computation using the value of an Option or OptionAsync . If the input is a None , it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.

@typeParamF - The function type to chain.@example

Some Case

import { Option } from 'byenull';

const option = Option.pipe(
Option.some(2),
Option.andThen((x) => Option.some(x * 2)),
);
// { type: 'Some', value: 4 }
@example

None Case (fn is never called)

import { Option } from 'byenull';

const option = Option.pipe(
Option.none(),
Option.andThen((x: number) => Option.some(x * 2)),
);
// { type: 'None' }
@example

Asynchronous Case

import { Option } from 'byenull';

type User = { id: string; name: string };

const fetchUser = Option.fn(async (id: string) =>
fetch(`/api/users/${id}`).then((response) => response.json() as Promise<User>),
);

const option = await Option.pipe(
Option.some('u123'),
Option.andThen(fetchUser),
);
// { type: 'Some', value: User }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
andThen
((
key: any
key
) =>
import Option
Option
.
function maybe<() => Promise<string | null>>(fn: () => Promise<string | null>): Option.OptionAsync<string> (+1 overload)

Executes a function and wraps its result in an Option or OptionAsync .

Nullish values and Promise rejections produce None ; synchronous throws are not captured.

@typeParamF - The function type to execute.@returnsAn Option or OptionAsync wrapping the function's return value.@example

Synchronous Thunk

import { Option } from 'byenull';

const option = Option.maybe(() => document.querySelector('#app'));
// { type: 'Some', value: HTMLElement } or { type: 'None' }
@example

Asynchronous Thunk

import { Option } from 'byenull';

type Config = { host: string };

const option = await Option.maybe(() =>
fetch('/api/config').then((response) => response.json() as Promise<Config>),
);
// { type: 'Some', value: Config }
@seefn - For wrapping functions that take parameters.@categoryCreators
maybe
(() =>
function readThrough(key: string): Promise<string | null>
readThrough
(
key: any
key
))), // async lookup
import Option
Option
.
function orElse<() => Option.OptionAsync<string>>(fn: () => Option.OptionAsync<string>): <O1>(option: O1) => Option.OptionFor<Option.OptionAsync<string> | O1, string | Option.InferSome<O1>>

Chains a fallback computation for an Option or OptionAsync . If the input is a Some , it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.

@typeParamF - The fallback function type.@example

None Case

import { Option } from 'byenull';

const option = Option.pipe(
Option.none(),
Option.orElse(() => Option.some('default')),
);
// { type: 'Some', value: 'default' }
@example

Some Case (fn is never called)

import { Option } from 'byenull';

const option = Option.pipe(
Option.some('value'),
Option.orElse(() => Option.some('default')),
);
// { type: 'Some', value: 'value' }
@seeunwrap - For returning a plain value instead of a fallback Option.@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
orElse
(() =>
import Option
Option
.
function maybe<() => Promise<string | null>>(fn: () => Promise<string | null>): Option.OptionAsync<string> (+1 overload)

Executes a function and wraps its result in an Option or OptionAsync .

Nullish values and Promise rejections produce None ; synchronous throws are not captured.

@typeParamF - The function type to execute.@returnsAn Option or OptionAsync wrapping the function's return value.@example

Synchronous Thunk

import { Option } from 'byenull';

const option = Option.maybe(() => document.querySelector('#app'));
// { type: 'Some', value: HTMLElement } or { type: 'None' }
@example

Asynchronous Thunk

import { Option } from 'byenull';

type Config = { host: string };

const option = await Option.maybe(() =>
fetch('/api/config').then((response) => response.json() as Promise<Config>),
);
// { type: 'Some', value: Config }
@seefn - For wrapping functions that take parameters.@categoryCreators
maybe
(() =>
function warmUp(): Promise<string | null>
warmUp
())), // async fallback
import Option
Option
.
function unwrap<string>(defaultValue: string): <O>(option: O & ([string] extends [Option.InferSome<O> | null | undefined] ? unknown : never)) => Option.Unwrapped<O, string, Option.InferSome<O>>

Extracts the value from an Option or OptionAsync . If the input is a None , the default value is returned.

@typeParamD - The default value type.@example

Some Case

import { Option } from 'byenull';

const value = Option.pipe(
Option.some(2),
Option.unwrap(0),
);
// 2
@example

None Case

import { Option } from 'byenull';

const empty: Option.Option<number> = Option.none();

const value = Option.pipe(
empty,
Option.unwrap(0),
);
// 0
@example

Nullish Default

import { Option } from 'byenull';

const value: number | null = Option.pipe(
Option.some(2),
Option.unwrap(null),
);
@seeorElse - For recovering with a fallback Option instead of a plain value.@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryUnwraps
unwrap
("anonymous"),
); // string

Unwrap an asynchronous Option

unwrap returns a Promise when its input is asynchronous, so await the call, or leave the Promise and continue in async code:

import { 
import Option
Option
} from "byenull";
const
const value: number
value
= await
import Option
Option
.
function unwrap<number>(defaultValue: number): <O>(option: O & ([number] extends [Option.InferSome<O> | null | undefined] ? unknown : never)) => Option.Unwrapped<O, number, Option.InferSome<O>>

Extracts the value from an Option or OptionAsync . If the input is a None , the default value is returned.

@typeParamD - The default value type.@example

Some Case

import { Option } from 'byenull';

const value = Option.pipe(
Option.some(2),
Option.unwrap(0),
);
// 2
@example

None Case

import { Option } from 'byenull';

const empty: Option.Option<number> = Option.none();

const value = Option.pipe(
empty,
Option.unwrap(0),
);
// 0
@example

Nullish Default

import { Option } from 'byenull';

const value: number | null = Option.pipe(
Option.some(2),
Option.unwrap(null),
);
@seeorElse - For recovering with a fallback Option instead of a plain value.@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryUnwraps
unwrap
(0)(
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
PromiseConstructor.resolve<Option.Option<number>>(value: Option.Option<number>): Promise<Option.Option<number>> (+2 overloads)

Creates a new resolved promise for the provided value.

@paramvalue A promise.@returnsA promise whose internal state matches the provided promise.
resolve
(
import Option
Option
.
function some<number>(value: number): Option.Option<number>

Creates a Some from a given value. Passing null or undefined returns None instead.

@typeParamT - The type of the value to wrap.@returnsA Some containing the value, or None if the value is nullish.@example
import { Option } from 'byenull';

const some = Option.some(42);
// { type: 'Some', value: 42 }

const none = Option.some(null);
// { type: 'None' }
@categoryCreators
some
(42)));
// 42

When you don't know whether a value is async

If a value's type is OptionMaybeAsync<T>, sometimes an Option and sometimes a Promise of one, the same functions still apply, and the result reflects both possibilities:

import { 
import Option
Option
} from "byenull";
declare const
const option: Option.OptionMaybeAsync<number>
option
:
import Option
Option
.
type OptionMaybeAsync<T> = Option.Option<T> | Promise<Option.Option<T>>

An option that may be either synchronous or asynchronous.

@typeParamT - The type of the Some value.@categoryCore Types
OptionMaybeAsync
<number>;
const
const value: number | Promise<number>
value
=
import Option
Option
.
function unwrap<number>(defaultValue: number): <O>(option: O & ([number] extends [Option.InferSome<O> | null | undefined] ? unknown : never)) => Option.Unwrapped<O, number, Option.InferSome<O>>

Extracts the value from an Option or OptionAsync . If the input is a None , the default value is returned.

@typeParamD - The default value type.@example

Some Case

import { Option } from 'byenull';

const value = Option.pipe(
Option.some(2),
Option.unwrap(0),
);
// 2
@example

None Case

import { Option } from 'byenull';

const empty: Option.Option<number> = Option.none();

const value = Option.pipe(
empty,
Option.unwrap(0),
);
// 0
@example

Nullish Default

import { Option } from 'byenull';

const value: number | null = Option.pipe(
Option.some(2),
Option.unwrap(null),
);
@seeorElse - For recovering with a fallback Option instead of a plain value.@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryUnwraps
unwrap
(0)(
const option: Option.OptionMaybeAsync<number>
option
);
// number | Promise<number>

To force a single path, normalize with await inside an async function first.