Task — Lazy Asynchronous Work
JavaScript Promise instances execute eagerly upon creation and can reject with untyped values (unknown). This makes it difficult to compose async workflows before execution or track errors in type signatures.
Task<A> is a zero-argument function returning an infallible Deferred<A>:
Because Task is a function, execution is deferred until invoked. Because Deferred<A> is typed to never reject, failures are tracked explicitly in return types via Task.Result<E, A>.
Creating Tasks
Section titled “Creating Tasks”We lift asynchronous values into a Task context depending on whether they are already resolved or require evaluation:
Because standard Promises in JavaScript are fallible by definition, Task.tryCatch is the canonical intake for operations that may reject or throw an exception, trapping errors with a fallback handler to ensure the returned Task<A> is infallible and never throws:
Transforming and Sequencing
Section titled “Transforming and Sequencing”We can transform and chain our asynchronous blueprints while they are still in their lazy, unexecuted state.
Transforming values with map
Section titled “Transforming values with map”map describes how the resolved value should change once the Task eventually runs, returning a new Task without triggering any execution:
Sequential chains with chain
Section titled “Sequential chains with chain”When a transformation itself returns another Task, we use chain to execute them sequentially and flatten the resulting context:
Concurrency Controls
Section titled “Concurrency Controls”Unlike raw Promises, which require manual coordination using Promise.all or Promise.race, Task provides clean, functional combinators for parallel, raced, or sequential execution.
Parallel execution with all
Section titled “Parallel execution with all”Task.all runs an array of Tasks simultaneously and collects all results into a typed tuple:
The return type is structurally matched to your input: passing [Task<Config>, Task<User>] yields a Task<[Config, User]> tuple.
Raced execution with race
Section titled “Raced execution with race”Task.race starts multiple Tasks simultaneously and resolves with the outcome of whichever Task completes first, abandoning the remaining in-flight tasks:
Sequential queueing with sequential
Section titled “Sequential queueing with sequential”When execution order matters, or when running tasks in parallel would trigger race conditions or overload resources, Task.sequential executes each Task in submission order:
Operational Utilities
Section titled “Operational Utilities”Delayed execution with delay
Section titled “Delayed execution with delay”Task.delay introduces a timed pause before the Task executes:
Standard cancellation with abortable
Section titled “Standard cancellation with abortable”Task.abortable wraps a promise factory, yielding a managed Task alongside a shared abort function. Invoking abort() immediately cancels any active, in-flight execution:
Calling task() while a previous invocation is still active will automatically abort the previous run.
Ending pipelines with run
Section titled “Ending pipelines with run”When composing inline pipelines, Task.run allows you to execute the Task at the terminal end of the pipe chain, returning a Deferred value that resolves to the output, and accepting an optional AbortSignal for external cancellation:
Polling and Repetition
Section titled “Polling and Repetition”Task provides built-in utilities to repeat executing a task, designed naturally around the guarantee that Tasks are infallible.
repeat executes a Task a fixed number of times, collecting all outcomes:
repeatUntil polls a Task repeatedly on an interval until the returned value satisfies a predicate:
The Task Family
Section titled “The Task Family”While Task<A> is excellent for operations that never fail, typical real-world async tasks involve network or database requests that can yield errors. For these, we use specialized variants within the Task family.
Task.Result
Section titled “Task.Result”Task.Result<E, A> represents a fallible async task, equivalent to Task<Result<E, A>> under the hood. It serves as the primary tool for most asynchronous applications:
Cancellation propagation in Task.Result chains
Section titled “Cancellation propagation in Task.Result chains”When sequencing multiple Task.Result steps, Task.Result.chain propagates the abort signal down the line automatically. An abort triggered at the call site immediately cancels whichever step is currently in flight:
Retrying fallible tasks with Task.Result.retry
Section titled “Retrying fallible tasks with Task.Result.retry”When network operations or database queries suffer transient failures, Task.Result.retry automatically re-evaluates the task according to a RetryPolicy:
If an attempt succeeds (Ok), execution completes immediately without further retries. If an attempt fails (Err), the policy calculates the delay before executing the next attempt, respecting any AbortSignal passed from the call site.
Lazy Task Memoization: Task.memoize
Section titled “Lazy Task Memoization: Task.memoize”Because Task blueprints are lazy thunks, calling a task multiple times will re-trigger the underlying async computation every time.
Task.memoize (as well as Task.Result.memoize, Task.Maybe.memoize, and Task.Validation.memoize) creates a memoized task that executes the operation at most once on the first call and caches the resolved result for all subsequent calls:
Task.Maybe
Section titled “Task.Maybe”Task.Maybe<A> represents an asynchronous operation that may yield nothing, equivalent to Task<Maybe<A>>:
When an asynchronous operation resolves to None (representing an absent resource or a failed lookup), you can recover gracefully by providing a fallback asynchronous operation using recover:
Task.Validation
Section titled “Task.Validation”Task.Validation<E, A> represents an asynchronous validation check that accumulates multiple errors, equivalent to Task<Validation<E, A>>:
Because validations accumulate multiple errors instead of failing fast, we often need to transform or perform side effects on the collected errors mid-pipeline. You can transform the error list using mapError, or execute a side effect (such as writing to a warning logger) using tapError:
Accumulating values: bind / bindTo
Section titled “Accumulating values: bind / bindTo”When you need to perform multiple sequential asynchronous operations and gather their results into a single object, nesting chain and map inside pipelines can become highly complex and hard to read:
To solve this, you can use bindTo and bind to cleanly accumulate asynchronous values key-by-key in a flat, readable pipeline. These helpers are available across the entire Task family: Task, Task.Result, and Task.Maybe.
bindTo lifts an asynchronous value into the pipeline’s accumulator object:
bind runs a new asynchronous operation using the accumulated object and attaches the result to a new key:
If any step fails (yielding None in Task.Maybe or Err in Task.Result), the entire pipeline short-circuits and propagates the failure immediately.
Combining async records: struct
Section titled “Combining async records: struct”While bind is perfect for sequential steps where a latter step depends on the output of a prior step, sometimes you have a set of independent asynchronous tasks that you want to combine into a single object. For this, you can use the struct helper, which is available on Task.Result, Task.Maybe, and Task.Validation.
struct combines a record of async tasks into a single task holding a record of success values. Under the hood, it evaluates all tasks in parallel (by calling them concurrently and using Promise.all internally) while correctly forwarding the AbortSignal down to each sub-task.
With Task.Result
Section titled “With Task.Result”If any individual field resolves to an Err, the entire struct short-circuits to that error. If multiple fields fail, Task.Result.struct returns the first error encountered in key order:
With Task.Maybe
Section titled “With Task.Maybe”Evaluates fields in parallel, resolving to Some record if all succeed, and returning None immediately if any task resolves to None:
With Task.Validation
Section titled “With Task.Validation”Evaluates validations in parallel and accumulates all validation errors across all failed branches, rather than short-circuiting:
Running Tasks at boundaries
Section titled “Running Tasks at boundaries”Because a Task is simply a function, you run it by invoking it. Invoking a Task<A> yields a Deferred<A>, which is highly compatible with the standard Promise ecosystem. You can await it directly within any standard async/await block:
If you are interfacing with external libraries or frameworks that strictly require a standard Promise instance, you can convert the Deferred value using Deferred.to.Promise:
Problems it solves
Section titled “Problems it solves”- Composing lazy asynchronous workflows: In background workers and server endpoints, asynchronous pipelines often involve multiple sequential steps (such as acquiring auth tokens, querying profile data, fetching permission lists, and writing audit records). Native promises execute eagerly upon creation.
Taskencapsulates asynchronous operations as lazy descriptions, enabling modular pipeline composition and transformation before initiating network or I/O work. - Coordinated concurrency and fallback racing: When aggregating data across distributed backends or caching layers, applications need fine-grained concurrency control.
Taskprovides structured combinators likeTask.allfor parallel fan-out,Task.racefor racing primary against fallback sources, andTask.sequentialfor queue execution, all while preserving functional purity. - Compiler-enforced async error handling with
Task.Result: Network calls and disk I/O naturally produce domain failures. StandardPromise.rejectdiscards TypeScript type information, allowing unhandled rejections to bubble up.Task.Resultpairs lazy asynchronous execution with typed errors, ensuring the outer task always resolves safely while forcing callers to handle specific failure variants. - Time-bound operations and scheduled polling (
Task.timeout,Task.delay,Task.repeat): Wrapping external network calls with timeout boundaries typically involves race hackery withsetTimeoutand cleanup listeners.Task.timeoutattaches strict duration limits returning typedResulterrors on expiration, whileTask.delayandTask.repeatconfigure scheduled interval polling cleanly. - Asynchronous optionality with
Task.Maybe: When loading cached tokens or reading optional database settings asynchronously, missing entries are expected.Task.Maybethreads async execution and optional absence together, allowing callers to map, chain, and recover without nested promise-and-null checks.