@nesvet/tasks
v1.2.1
Published
Tasks
Readme
@nesvet/tasks
A small typed task registry built on EventEmitter: you define a glossary of Task subclasses, run them by name with Tasks.do, and listen for lifecycle events. Depends on eventemitter3 and @nesvet/n for helpers and typed errors.
Install
npm install @nesvet/tasksUsage
import { Task, Tasks } from "@nesvet/tasks";
class EchoTask extends Task<string> {
async do(message: string) {
return message.toUpperCase();
}
}
const tasks = Tasks.init({ echo: EchoTask });
tasks.on("echo.begin", (task) => {
// …
});
const task = tasks.do("echo", "hello");
const result = await task.whenExecuted();Subclass do receives the arguments you pass to tasks.do(name, …args).
API
Task<Result> — execute() runs do(...args) once; setState merges into state and emits state; abort sets error and calls optional onAbort; whenExecuted() returns the result promise. Fields: args, status (idle | executing | success | error), state (result, error, plus your keys). Events: executing, state, success, error.
Tasks<Glossary> — do(name, …args) starts a task (or returns the existing run if the same name and same args are already running); running is a Map of active instances; availableParallelism mirrors os.availableParallelism. Factory: Tasks.init(glossary, options?). Per-task events use the task key as a prefix, for example echo.begin, echo.end, echo.state, and echo.error; the registry also emits error for uncaught failures.
Options — verbose?: boolean logs each setState payload to the console.
License
MIT — repository.
