Skip to content

API Reference

This page is generated from the awaitly package JSDoc and TypeScript types. For workflow and step options, see Options reference below.

You can use named exports (tree-shake friendly) or the Awaitly namespace. For minimal bundle (Result types only, no namespace), use awaitly/result:

// Minimal bundle: Result types only
import { ok, err, map, andThen, type AsyncResult } from 'awaitly/result';
// Result retry (standalone, no workflow engine)
import { tryAsyncRetry, type RetryConfig } from 'awaitly/result/retry';
// Full package: named exports
import { ok, err, pipe, map, type AsyncResult } from 'awaitly';
// Full package: Awaitly namespace (Effect-style single object)
import { Awaitly } from 'awaitly';
Awaitly.ok(1); Awaitly.err('E'); Awaitly.pipe(2, (n) => n * 2);

Creates a failed Result.

When to use: Return a typed failure without throwing so callers can handle it explicitly.

err(error: E, options?: unknown): Err<E, C>

Creates a successful Result.

When to use: Wrap a successful value in a Result for consistent return types.

ok(): Ok<void>

Checks if a Result is a failure.

When to use: Prefer functional-style checks or array filtering.

isErr(r: Result<T, E, C>): (value: Err<E, C>) => boolean

Checks if a Result is successful.

When to use: Prefer functional-style checks or array filtering.

isOk(r: Result<T, E, C>): (value: Ok<T>) => boolean

Checks if an error is an UnexpectedError.

When to use: Distinguish unexpected failures from your typed error union.

isUnexpectedError(e: unknown): (value: UnexpectedError) => boolean

Extracts the value from an Ok result, or throws UnwrapError if it’s an Err.

When to use: Only at boundaries or tests where a failure should be fatal.

unwrap(r: Result<T, E, C>): T

Extracts the value from an Ok result, or returns a default value if it’s an Err.

When to use: Provide a safe fallback without branching.

unwrapOr(r: Result<T, E, C>, defaultValue: T): T

Extracts the value from an Ok result, or calls a function to get a default value if it’s an Err.

When to use: Compute a fallback from the error (logging, metrics, or derived defaults).

unwrapOrElse(r: Result<T, E, C>, fn: (error: E, cause?: C) => T): T

Wraps a synchronous function that might throw into a Result.

When to use: Wrap sync code that might throw so exceptions become Err values.

from(fn: () => T): Err<unknown, unknown> | Ok<T>

Converts a nullable value into a Result.

When to use: Turn null/undefined into a typed error before continuing.

fromNullable(value: T | unknown | undefined, onNull: () => E): Result<T, E>

Wraps a Promise into a Result.

When to use: Wrap a Promise and keep the raw rejection as Err; use tryAsync to map errors.

fromPromise(promise: Promise<T>): Promise<Err<unknown, unknown> | Ok<T>>

Wraps an async function that might throw into an AsyncResult.

When to use: Wrap async work and map thrown/rejected values into your typed error union.

tryAsync(fn: () => Promise<T>): AsyncResult<T, unknown>

Chain Result-returning functions.

When to use: Chain dependent operations that return Result without nested branching.

andThen(r: Ok<T>, fn: (value: T) => Ok<U>): Ok<U>

Transforms the value inside an Ok result.

When to use: Transform only the Ok value while leaving Err untouched.

map(r: Ok<T>, fn: (value: T) => U): Ok<U>

Transforms the error inside an Err result.

When to use: Retype or normalize errors while leaving Ok values unchanged.

mapError(r: Result<T, E, C>, fn: (error: E, cause?: C) => F): Result<T, F, C>

Transform error with a function that might throw.

When to use: Transform errors when the mapping might throw and you want that captured.

mapErrorTry(r: Result<T, E, C>, fn: (error: E) => F, onError: (thrown: unknown) => G): Result<T, F | G, unknown>

Transform value with a function that might throw.

When to use: Transform Ok values with a function that might throw and capture the failure.

mapTry(r: Result<T, E, C>, fn: (value: T) => U, onError: (thrown: unknown) => F): Result<U, E | F, unknown>

Pattern match on a Result.

When to use: Handle both Ok and Err in a single expression that returns a value.

match(r: Ok<T>, handlers: unknown): R

Provide an alternative Result if the first is an Err.

When to use: Recover from Err by returning a fallback Result or retyping the error.

orElse(r: Result<T, E, C>, fn: (error: E, cause?: C) => Result<T, E2, C2>): Result<T, E2, C | C2>

Execute a side effect on Ok values.

When to use: Add side effects (logging, metrics) on Ok without changing the Result.

tap(r: Result<T, E, C>, fn: (value: T) => void): Result<T, E, C>

Execute a side effect on Err values.

When to use: Add side effects (logging, metrics) on Err without changing the Result.

tapError(r: Result<T, E, C>, fn: (error: E, cause?: C) => void): Result<T, E, C>

Pipe a value through a series of functions left-to-right.

pipe(a: A): A

Compose functions left-to-right (returns a function).

flow(ab: (a: A) => B): (a: A) => B

Compose functions right-to-left.

compose(ab: (a: A) => B): (a: A) => B

Identity function - returns its argument unchanged.

identity(a: A): A

Curried Result combinators for use in pipe().

Recover from error with another Result.

recoverWith(result: Result<T, E1, C1>, fn: (error: E1) => Result<T, E2, C2>): Result<T, E2, C1 | C2>

Get the value or a default.

getOrElse(result: Result<T, E, C>, defaultValue: T): T

Get the value or compute a default lazily.

getOrElseLazy(result: Result<T, E, C>, fn: () => T): T

Transform success value asynchronously.

mapAsync(result: Result<T, E, C> | AsyncResult<T, E, C>, fn: (value: T) => Promise<U>): AsyncResult<U, E, C>

Async flatMap.

flatMapAsync(result: Result<T, E1, C1> | AsyncResult<T, E1, C1>, fn: (value: T) => AsyncResult<U, E2, C2>): AsyncResult<U, E1 | E2, C1 | C2>

Async tap - side effect on success.

tapAsync(result: Result<T, E, C> | AsyncResult<T, E, C>, fn: (value: T) => Promise<void>): AsyncResult<T, E, C>

Async tapError - side effect on error.

tapErrorAsync(result: Result<T, E, C> | AsyncResult<T, E, C>, fn: (error: E) => Promise<void>): AsyncResult<T, E, C>

Race async results - first to complete wins.

Handles rejected promises by converting them to err() results with type PROMISE_REJECTED.

race(results: AsyncResult<T, E, C>[]): AsyncResult<T, PromiseRejectedError | E, PromiseRejectionCause | C>

Sequence an array through a Result-returning function. Stops on first error.

traverse(items: T[], fn: (item: T, index: number) => Result<U, E, C>): Result<U[], E, C>

Async version of traverse.

traverseAsync(items: T[], fn: (item: T, index: number) => AsyncResult<U, E, C>): AsyncResult<U[], E, C>

Parallel traverse - executes all in parallel, fails fast.

Returns immediately when any result fails, without waiting for pending operations. Only returns all values if every result succeeds.

traverseParallel(items: T[], fn: (item: T, index: number) => AsyncResult<U, E, C>): AsyncResult<U[], PromiseRejectedError | E, PromiseRejectionCause | C>

Standalone retry for async operations without the full workflow engine. Import from awaitly/result/retry.

Wraps an async function that might throw into an AsyncResult, with retry support.

When to use: Wrap async work with retry logic for transient failures without needing the full workflow engine.

tryAsyncRetry(fn: () => Promise<T>, config: { retry: RetryConfig<unknown> }): AsyncResult<T, unknown>
tryAsyncRetry<T, E>(fn: () => Promise<T>, onError: (cause: unknown) => E, config: { retry: RetryConfig<E> }): AsyncResult<T, E>

Configuration for retry behavior: times (attempts), delayMs, backoff ('constant' | 'linear' | 'exponential'), optional shouldRetry(error) predicate.

type RetryConfig<E = unknown> = { times: number; delayMs: number; backoff?: 'constant' | 'linear' | 'exponential'; shouldRetry?: (error: E) => boolean }

Single place for all workflow and step option keys (for docs and static analysis).

Workflow — The value returned by createWorkflow has a single method: workflow.run(name?, fn, config?). Overloads: run(fn), run(fn, config), run(name, fn), run(name, fn, config). Options below can be passed at creation (createWorkflow('name', deps, options)) or per-run in RunConfig (workflow.run(fn, config)).

OptionTypePurpose
descriptionstring?Short description for labels/tooltips and doc generation
markdownstring?Full markdown documentation for static analysis and docs
strictboolean?Closed error union
catchUnexpectedfunction?Map unexpected errors to typed union
onEventfunction?Event stream callback
createContextfunction?Custom context factory
cacheStepCache?Step caching backend (creation-time only)
resumeStateResumeState?Resume from saved state
depsPartial<Deps>?Per-run override of creation-time deps (RunConfig only)
signalAbortSignal?Workflow cancellation
streamStoreStreamStore?Streaming backend
snapshotWorkflowSnapshot?Restore from saved snapshot (RunConfig or creation)
onUnknownSteps`‘warn''error'
onDefinitionChange`‘warn''error'

Persistence: Use createResumeStateCollector(), pass collector.handleEvent to onEvent, then call collector.getResumeState() after a run to persist. Restore with workflow.run(fn, { resumeState }) or creation-time resumeState (or snapshot where supported).

Step (step, step.sleep, step.retry, step.withTimeout) — in options object:

OptionTypePurpose
namestring?Human-readable step name for tracing
keystring?Cache key for resume/caching
descriptionstring?Short description for docs and static analysis
markdownstring?Full markdown for step documentation
ttlnumber?Cache TTL (step.sleep and cached steps)
retryobject?Retry config (step.retry)
timeoutobject?Timeout config (step.withTimeout)
signalAbortSignal?Step cancellation (e.g. step.sleep)

Saga step (saga.step / saga.tryStep) — first argument is the step name (string). Optional third argument is an options object:

OptionTypePurpose
descriptionstring?Short description for docs and static analysis
markdownstring?Full markdown for step documentation
compensatefunction?Compensation function on rollback