Sync/Async-Adaptive Utilities
How to write utilities that are as synchronous as their inputs: pass all-sync
functions and you get plain values back (no await, no microtasks); make any
piece async — even one stage — and results become Promises, reflected in the
types.
Used by: createCursorCodec,
createPaginator, tryCatch,
collect, enumerate,
resolveFieldOptions — a resource field’s
options may be a static list or a sync/async getter (FieldOptions).
Background
Section titled “Background”- The problem is what Bob Nystrom’s “What Color is Your
Function?”
describes: async is viral. One async dependency forces
asyncon every caller, and anasyncwrapper around sync logic taxes it with pointless microtasks. - The objection is “releasing Zalgo” (Isaac Schlueter): APIs that are unpredictably sometimes-sync, sometimes-async are bug factories.
- The resolution: determine asyncness per instance, at construction
time, visible in the types. A given codec/paginator/predicate is always
one color; callers never guess. This is effect polymorphism over
MaybePromise, not Zalgo.
For FP readers: chainMaybePromise is monadic flatMap where the monad is
Identity | Promise.
The Rules
Section titled “The Rules”- Construction-time color. Factories and combinators decide sync vs async from their inputs’ types, once. Never flip color per call based on data.
- Types tell the truth. All-sync inputs → sync return types. Anything
async →
Promise/MaybePromisereturn types. Use overloads (sync overload first) so TypeScript picks the precise signature. - Sync stays sync. The sync path must never touch the microtask queue —
no
asynckeyword on the implementation, noawait, noPromise.resolvewrapping. Compose withchainMaybePromise/isPromiseinstead. awaitalways works. Becauseawaiton a plain value is a no-op, callers who don’t care about the distinction can always writeawaitand stay correct, whatever the color.- Throw programmer errors synchronously. Misconfiguration (missing capability, invalid options) throws immediately in both colors. Only data errors follow the value’s color (sync throw vs rejected Promise).
Building Blocks (all in core)
Section titled “Building Blocks (all in core)”import type { MaybePromise } from "@xtandard/lib"; // T | PromiseLike<T>import { isPromise, chainMaybePromise, resolveMaybePromise } from "@xtandard/lib";isPromise(value)— thenable guard; the runtime color test.chainMaybePromise(value, fn)— applyfnnow ifvalueis plain,.thenit if it’s a Promise. The composition primitive; an all-sync chain never schedules a microtask.resolveMaybePromise(value)— always-async normalizer, for the boundary where you want a Promise (e.g. feeding TanStack Query).
chainMaybePromise(value, fn) decides per value:
flowchart LR
V["value: MaybePromise#lt;T#gt;"] --> IP{"isPromise(value)?"}
IP -->|no| SYNC["fn(value) right now<br/>(no microtask)"]
IP -->|yes| ASYNC["value.then(fn)<br/>returns a Promise"]
Recipe 1 — Adaptive factory (the codec/paginator shape)
Section titled “Recipe 1 — Adaptive factory (the codec/paginator shape)”Three pieces: paired option types, paired result types, overloads + one implementation in the loosest types.
// 1. Option types: a strict-sync variant and a MaybePromise variantexport type ThingOptionsSync<T> = { transform?: (data: T) => string };export type ThingOptions<T> = { transform?: (data: T) => MaybePromise<string> };
// 2. Result types mirroring themexport type Thing<T> = { run: (data: T) => string };export type ThingMaybeAsync<T> = { run: (data: T) => MaybePromise<string> };
// 3. Overloads — sync FIRST (TS picks the first match), impl in loose typesexport function createThing<T>(options?: ThingOptionsSync<T>): Thing<T>;export function createThing<T>(options: ThingOptions<T>): ThingMaybeAsync<T>;export function createThing<T>(options: ThingOptions<T> = {}): ThingMaybeAsync<T> { const { transform = JSON.stringify } = options; return { run: (data) => chainMaybePromise(transform(data), postProcess) };}Why this works: a sync function (d) => string is assignable to
(d) => MaybePromise<string> (covariant return), so sync configs match both
overloads — and TypeScript takes the first. An async function only matches
the second. The sync caller gets string, the async caller gets honest types,
and there is exactly one implementation.
flowchart TD
CALL["createThing(options)"] --> MATCH{"options match<br/>ThingOptionsSync#lt;T#gt;?"}
MATCH -->|"yes: all callbacks sync"| O1["overload 1 (listed first)<br/>Thing#lt;T#gt;: run() returns string"]
MATCH -->|"no: some callback async"| O2["overload 2<br/>ThingMaybeAsync#lt;T#gt;: run() returns MaybePromise#lt;string#gt;"]
O1 --> IMPL["one implementation,<br/>composed with chainMaybePromise"]
O2 --> IMPL
Variant: distributive conditional return
Section titled “Variant: distributive conditional return”For a single function (no factory), a conditional return type can replace the
overload pair and even handles MaybePromise unions precisely, because
conditional types distribute over unions — see tryCatch:
type IsAny<T> = 0 extends 1 & T ? true : false;
export type TryCatchReturn<R, E = Error> = IsAny<R> extends true ? Result<R, E> // any guard — JSON.parse etc. : [R] extends [never] ? Result<never, E> // never guard — function that always throws : R extends PromiseLike<infer U> ? Promise<Result<U, E>> // () => Promise<T> → Promise<Result<T>> : Result<R, E>; // () => T → Result<T>// () => MaybePromise<T> distributes to Result<T> | Promise<Result<T>> — exact.
export function tryCatch<R, E = Error>(fn: () => R): TryCatchReturn<R, E>;Two guards matter, both for inputs that poison distribution:
never(a function that always throws): a distributive conditional overnevercollapses the whole return type tonever. Guard with the non-distributive[R] extends [never].any(e.g.() => JSON.parse(...)):anydistributes into both branches, producingResult<any> | Promise<Result<any>>— which is not destructurable. Detect with the0 extends 1 & Ttrick and short-circuit.
Also add a final catch-all union overload ((input: A | B) => loose) —
without it, a value typed as a union of the overload parameter types fails
overload resolution entirely (collect, enumerate, and tryCatch all
carry one).
Make sure your type assertions are actually checked. These bugs shipped green because
tsconfig.jsonoriginally only includedsrc/— theexpectTypeOftests were never typechecked. Includetest/**in the tsconfig thatcheckruns.
Capability tiers
Section titled “Capability tiers”When different parts of the config affect different outputs independently,
add a middle overload instead of collapsing everything to one async-ness.
createPaginator has three tiers because cursorFor’s color depends only on
the codec while paginate’s depends on fetchers and codec:
| Config | paginate() |
cursorFor() |
|---|---|---|
| sync fetchers + sync codec | Paginated<T> |
string |
| async fetchers + sync codec | MaybePromise<Paginated<T>> |
string |
| async codec anywhere | MaybePromise<Paginated<T>> |
MaybePromise<string> |
The payoff: downstream sync-only consumers (toRelayConnection needs a sync
cursorFor) keep compiling in the common async-fetcher case, and break — at
compile time, with a clear error — only when someone actually introduces an
async codec.
Recipe 2 — Adaptive combinator (the rule/predicate shape)
Section titled “Recipe 2 — Adaptive combinator (the rule/predicate shape)”For variadic/iterative logic (combinators over many functions), walk synchronously and escape to an async closure at the first Promise:
export function all<TData>(...rules: Array<(d: TData) => boolean>): (d: TData) => boolean;export function all<TData>( ...rules: Array<(d: TData) => MaybePromise<boolean>>): (d: TData) => MaybePromise<boolean>;export function all<TData>(...rules: Array<(d: TData) => MaybePromise<boolean>>) { return (data: TData): MaybePromise<boolean> => { for (const [index, rule] of rules.entries()) { const result = rule(data); if (isPromise(result)) { // first Promise seen: hand the rest to an async closure return (async () => { if (!(await result)) return false; for (const rest of rules.slice(index + 1)) { if (!(await rest(data))) return false; } return true; })(); } if (!result) return false; // sync short-circuit, zero microtasks } return true; };}Properties to preserve: short-circuiting works in both colors, evaluation order is identical in both colors, and the sync prefix of a mixed list still runs synchronously.
Joining parallel values
Section titled “Joining parallel values”Promise.all only when something actually is a Promise:
const a = encode(x);const b = encode(y);return isPromise(a) || isPromise(b) ? Promise.all([a, b]).then(([a, b]) => use(a, b)) : use(a, b); // both narrowed to stringGotchas
Section titled “Gotchas”isPromisenarrows toPromiseLike<T>, notPromise<T>. Its else-branch narrows aMaybePromise<T>toT, even for a type parameter, so noas Tcast is needed. In the true branch, chain with.then(orawait);.catch/.finallyaren’t onPromiseLike.- Overload order matters. Sync overload first, loosest last. The implementation signature is not callable; make it the loosest shape.
- Don’t mark the implementation
async. Oneasynckeyword silently re-colors every call. The implementation composes withchainMaybePromiseonly. Same for strayawaits andPromise.resolve()wraps. - Watch
.then-flattening.chainMaybePromiseflattens likeflatMap— afnreturningPromise<R>over a sync value yieldsPromise<R>, notPromise<Promise<R>>. That’s what you want; don’t “fix” it. - Mutating callbacks: a callback inside
chainMaybePromisemay run synchronously or later. Don’t close over mutable state that callers can change between call and settlement. - Error semantics shift. Replacing
async functionwith adaptive composition turns pre-fetch validation errors from rejected Promises into sync throws. Tests using.rejects.toThrowfor those must becomeexpect(() => ...).toThrow(this bit us inpagination.test.ts). - Boundary APIs that require Promises (TanStack Query
queryFn, etc.): normalize at the edge withPromise.resolve(adaptiveCall())— never inside the adaptive code.
Testing Checklist
Section titled “Testing Checklist”Test both colors, both at runtime and at the type level (vitest’s
expectTypeOf). Two-color test blocks live in each util’s own test file
(repo convention: test file matches source file) — see the
“sync/async adaptive” describes in test/pagination.test.ts,
test/cursor-codec.test.ts, and
test/resolve-maybe-promise.test.ts.
// runtime: sync path returns a plain valueconst result = thing.run(data);expect(isPromise(result)).toBe(false);
// types: overload picked the sync signatureexpectTypeOf(result).toEqualTypeOf<string>();
// runtime + types: one async stage flips the colorconst asyncThing = createThing({ transform: async (d) => "..." });expect(isPromise(asyncThing.run(data))).toBe(true);- All-sync config: result is not a Promise (
isPromisefalse) and the sync type is inferred (expectTypeOf). - One async stage: result is a Promise; loose type inferred.
- Mixed configs hit the intended middle tier (if any).
- Behavior is identical in both colors (run the same assertions through
both,
awaitworks on each). - Config errors throw synchronously in both colors.
- Short-circuit/ordering semantics match in both colors (combinators).
When NOT to use it
Section titled “When NOT to use it”- Inherently async work (network, fs, timers): just be async. Adaptive machinery with no possible sync caller is complexity for nothing.
- The color is structural, chosen by the caller’s syntax.
defer/deferSyncstay explicit because they implement different disposal protocols (Symbol.asyncDisposevsSymbol.dispose) consumed by different syntax (await usingvsusing) — there is no single implementation that serves both. - The “async version” has genuinely different semantics.
enumerateAsyncsurvives alongside adaptiveenumeratebecausefor awaitawaits Promise values inside a sync iterable — that’s a behavior choice, not a color. (tryCatchSynchad no such distinction — the adaptivetryCatchsubsumes it entirely, so it’s@deprecatedand kept only for backwards compatibility.) - Hot one-liners where two tiny separate functions are clearer than overload machinery.
Rule of thumb: adapt when one implementation genuinely serves both colors and callers plug in their own functions (factories, combinators, pipelines).
Migration checklist (making an existing util adaptive)
Section titled “Migration checklist (making an existing util adaptive)”- Widen callback option types to return
MaybePromise<...>; add a strict-sync options type alongside. - Add paired result types (sync +
MaybeAsync). - Add overloads: sync → sync, (middle tiers), loosest → loosest.
- De-
asyncthe implementation: replaceawaitchains withchainMaybePromise, parallelawaits with theisPromise-guardedPromise.alljoin, loops with the escape-to-async-closure walk. - Keep programmer-error
throws outside the chains so they stay sync. - Re-check tests for
.rejectsassertions that must become synctoThrow. - Add the two-color test block (runtime +
expectTypeOf).