Task
Coordinates concurrent asynchronous work.
Table of contents
Category
Value
Import
jsimport { Task } from "valyrian.js/tasks";Public signature
tsnew Task<TArgs = void, TResult = unknown>(handler: TaskHandler<TArgs, TResult>, options?: TaskOptions<TArgs, TResult>): Task<TArgs, TResult>API form
Task is a class. Construct it with one synchronous or asynchronous handler and run it with the argument type declared by TArgs.
Options and state
tstype TaskContext = { signal: AbortSignal };
type TaskHandler<TArgs, TResult> = (
args: TArgs,
context: TaskContext,
) => Promise<TResult> | TResult;
type TaskOptions<TArgs, TResult> = {
strategy?: "takeLatest" | "enqueue" | "drop" | "restartable";
onSuccess?: (result: TResult, args: TArgs) => void;
onError?: (error: unknown, args: TArgs) => void;
};
type TaskState<TResult> = {
status: "idle" | "running" | "success" | "error" | "cancelled";
running: boolean;
result: TResult | null;
error: unknown;
};Default strategy
The default strategy is takeLatest. It starts the latest run and prevents stale completion from replacing current state. enqueue serializes calls, drop returns the stored result while work is active, and restartable cancels the previous run before starting the next one.
Essential properties and methods
tsreadonly state: TaskState<TResult>
run(args: TArgs): Promise<TResult | null>
data(): TResult | null
error(): unknown
cancel(): void
reset(): void
on("state" | "success" | "error" | "cancel", callback): () => void
off(event, callback): voidCancellation and errors
A handler rejection sets error state, emits error and rejects run(). Cancellation sets cancelled and resolves the run with the previous result, or null when no result exists. reset() restores idle state and clears result and error.