Task — Lazy Asynchronous Work
4.04 kB minified + gzipped
JavaScript Promise instances execute eagerly upon creation and reject with untyped values (unknown):
Task<A> models an asynchronous computation as a lazy, infallible function that accepts an optional AbortSignal and returns a Deferred<A>:
Execution is deferred until the function is called. Because Deferred<A> is typed never to reject, failures are tracked explicitly in return types via Task.Result<E, A>.
flowchart TB
subgraph PromiseModel ["Native Promise (Eager Execution)"]
P1["loadUserData(userId) called"] --> P2["Immediately in-flight on network"]
P2 --> P3["Promise(User) settles (rejections untyped as unknown)"]
end
subgraph TaskModel ["Task (Lazy Execution Blueprint)"]
T1["formattedTime pipeline defined"] --> T2["Inert blueprint (zero execution)"]
T2 -->|"Explicit call: formattedTime(signal)"| T3["Executes on demand"]
T3 --> T4["Deferred(A) (infallible resolution)"]
end
P3 ~~~ T1
Creating Tasks
Section titled “Creating Tasks”Task values are constructed from immediate constants, lazy synchronous thunks, or fallible promise factories:
For asynchronous operations that may throw or reject, Task.tryCatch traps errors with a fallback handler, guaranteeing the resulting Task<A> never rejects:
If the fallback handler returns an alternative sentinel type (such as null), TypeScript widens the return type automatically:
Transforming, Sequencing, and Side Effects
Section titled “Transforming, Sequencing, and Side Effects”Transformations, chains, and side-effect taps compose before execution starts.
Transforming values with map
Section titled “Transforming values with map”map transforms the resolved value once the Task runs, returning a new Task without initiating execution:
Sequential chains with chain
Section titled “Sequential chains with chain”When a transformation returns another Task, chain sequences them in order and flattens the result:
Combining independent tasks with apply
Section titled “Combining independent tasks with apply”When a curried function is wrapped in a Task, Task.apply runs the function task and its argument tasks in parallel, applying the resolved arguments:
Side effects with tap
Section titled “Side effects with tap”Task.tap executes a side-effect callback on the resolved value without altering the Task output:
Concurrency Controls
Section titled “Concurrency Controls”Task provides composable combinators for parallel, raced, and sequential execution with automatic AbortSignal propagation.
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 structurally matches the input: passing [Task<Config>, Task<User>] yields Task<[Config, User]>.
To limit concurrency, pass { concurrency }:
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, automatically aborting the remaining in-flight tasks via their AbortSignal:
Heterogeneous task types are preserved as a union: racing Task<number> and Task<string> evaluates to Task<number | string>.
Sequential execution with sequential
Section titled “Sequential execution with sequential”When execution order matters, or when parallel execution would cause race conditions, Task.sequential executes tasks one at a time 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:
Enforcing deadlines with timeout
Section titled “Enforcing deadlines with timeout”Task.timeout converts an infallible Task<A> into a fallible Task.Result<E, A>, resolving to Err(onTimeout()) if the task does not complete within the specified Duration and aborting the inner AbortSignal:
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.
Progress tracking and diagnostic labels: withProgress and withLabel
Section titled “Progress tracking and diagnostic labels: withProgress and withLabel”Task.withProgress invokes a callback with 0 immediately before the task starts and 1 when it resolves. Task.withLabel attaches a read-only .label property to a Task, preserving the literal label string in editor hover tooltips:
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 combinators for repeating and polling operations:
repeat executes a Task a fixed number of times, collecting all outcomes:
poll re-runs a Task on an interval until the returned value satisfies a predicate, returning that final value:
The Task Family
Section titled “The Task Family”Asynchronous network requests, disk operations, and external services can fail or return missing values. The Task namespace provides specialized container modules for these patterns:
Task.Result<E, A>for operations with typed errors.Task.Maybe<A>for operations that may yield no value.Task.Validation<E, A>for parallel operations that accumulate multiple errors.
Task.Result
Section titled “Task.Result”Task.Result<E, A> is a type alias for Task<Result<E, A>>.
flowchart TB
Input(["Task.Result.tryCatch(...)"]) --> Exec["Invoke Task: (signal) => Deferred"]
Exec --> Railway{"Async Outcome"}
Railway -->|"Async Success"| Ok["Result.Ok(A)"]
Railway -->|"Async Catch / Trap"| Err["Result.Err(E)"]
Ok -->|"Task.Result.chain / map"| Step2["Next Fallible Async Step"]
Err -->|"Short-circuit (bypassed)"| ErrFinal["Propagated Result.Err(E)"]
Step2 -->|"Success"| OkFinal["Result.Ok(B)"]
Step2 -->|"Failure"| ErrFinal
Creating and converting Task.Result
Section titled “Creating and converting Task.Result”Construct a Task.Result directly with make.ok and make.err, wrap a throwing or rejecting promise factory with tryCatch, or lift existing values via from.Result, from.Maybe, and from.nullable:
For network calls and fallible I/O, use Task.Result.tryCatch:
To discard the error channel and convert a Task.Result<E, A> into a Task.Maybe<A>, use Task.Result.to.Maybe:
Transforming, recovering, and extracting Task.Result
Section titled “Transforming, recovering, and extracting Task.Result”Task.Result mirrors the full Result combinator surface over async execution (map, mapError, bimap, chain, apply, ensure, tap, tapError, recover, recoverUnless, match, getOrElse, run):
When combining independent fallible tasks via a curried function, Task.Result.apply runs them in parallel:
Cancellation and Timeouts in Task.Result
Section titled “Cancellation and Timeouts in Task.Result”When sequencing multiple Task.Result steps, Task.Result.chain propagates the AbortSignal down the line automatically. You can also enforce a deadline on any Task.Result using Task.Result.timeout, and execute the pipeline using Task.Result.run(signal):
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:
To fail fast on permanent client errors while retrying transient server errors, pass a when predicate to the policy constructor:
Non-short-circuiting batching with allSettled
Section titled “Non-short-circuiting batching with allSettled”When evaluating multiple independent fallible requests in parallel, Task.Result.struct short-circuits on the first error encountered. If you need all tasks to run to completion regardless of individual failures (such as health check probes or bulk batch processing), use Task.Result.allSettled:
Task.Maybe
Section titled “Task.Maybe”Task.Maybe<A> represents an asynchronous operation that may yield nothing, equivalent to Task<Maybe<A>>.
You can construct a Task.Maybe with Task.Maybe.make.some, Task.Maybe.make.none, Task.Maybe.tryCatch (which turns rejections into None), or lift values via Task.Maybe.from.Maybe, Task.Maybe.from.nullable, Task.Maybe.from.Result, and Task.Maybe.from.Task:
Task.Maybe supports map, chain, apply, filter, tap, recover, match, getOrElse, to.Result, and run:
Task.Validation
Section titled “Task.Validation”Task.Validation<E, A> represents an asynchronous validation check that accumulates multiple errors across parallel checks, equivalent to Task<Validation<E, A>>.
Create a Task.Validation using make.passed, make.failed, make.failedAll, tryCatch, or lift existing containers via from.Validation, from.Result, from.Maybe, and from.nullable:
Task.Validation provides map, mapError, apply, struct, tap, tapError, recover, recoverUnless, match, getOrElse, to.Result, to.Maybe, and run:
Lazy Task Memoization: Task.memoize
Section titled “Lazy Task Memoization: Task.memoize”Calling a Task executes the underlying asynchronous computation on every invocation.
Task.memoize (along with Task.Result.memoize, Task.Maybe.memoize, and Task.Validation.memoize) caches the resolved result on the first call, returning it immediately on subsequent calls without re-executing:
Accumulating values: assign / assignTo
Section titled “Accumulating values: assign / assignTo”Sequential asynchronous operations that build up a combined record can be expressed with assignTo and assign without nested callbacks. Available across Task, Task.Result, and Task.Maybe:
assignTo wraps an asynchronous value into the pipeline’s accumulator object:
assign 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”For independent asynchronous tasks that can execute in parallel, struct combines a record of tasks into a single task holding a record of success values. Available on Task.Result, Task.Maybe, and Task.Validation.
All fields evaluate in parallel, 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 a function, you run it by invoking it (or passing it to Task.run(signal)). Invoking a Task<A> yields a Deferred<A>, which you can await 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, without mutating external state before execution. - Compiler-enforced async error handling with
Task.Result: Network calls and disk I/O 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,Task.poll): Wrapping external network calls with timeout boundaries typically involves race boilerplate withsetTimeoutand cleanup listeners.Task.timeoutandTask.Result.timeoutattach strict duration limits returning typedResulterrors on expiration, whileTask.delay,Task.repeat, andTask.pollconfigure 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.