husbandry
v0.1.3
Published
Structured concurrency for async tasks — spawn siblings under one scope; first failure cancels the rest via AbortSignal, then the scope throws after all have settled.
Maintainers
Readme
husbandry
Structured concurrency for async tasks — spawn siblings under one scope; first failure cancels the rest via AbortSignal, then the scope throws after all have settled.
The Problem
Promise.all starts everything but on first rejection it doesn't cancel the siblings — they keep running, leaking work, sockets, and money. Unhandled rejections surface later. Doing "run these together; if one fails, cancel the rest and clean up; await everything before returning" correctly is fiddly and re-invented constantly.
JavaScript has no native structured concurrency (unlike Python's trio/asyncio.TaskGroup or Kotlin coroutines). AbortController gives you the mechanism but not the lifecycle. Husbandry fills this gap with a tiny, zero-dependency package.
Install
npm install husbandry
# or
pnpm add husbandry
# or
yarn add husbandryUse
import husbandry from "husbandry";
// Basic usage
const results = await husbandry(async (spawn, signal) => {
const task1 = spawn(() => fetchA(signal));
const task2 = spawn(() => fetchB(signal));
const task3 = spawn(() => fetchC(signal));
return await Promise.all([task1, task2, task3]);
});With timeout composition:
import husbandry from "husbandry";
const controller = new AbortController();
const timeout = AbortSignal.timeout(5000); // 5 second timeout
const combinedSignal = AbortSignal.any([controller.signal, timeout]);
const results = await husbandry(async (spawn, signal) => {
const response = await spawn(() => fetch("/api/data", { signal }));
return response.json();
}, { signal: combinedSignal });API
husbandry<R>(body, options?): Promise<R>
Creates a structured concurrency group for async tasks.
- body: Function that receives
spawnandsignal, returns the group result - options.signal: External cancellation signal propagated into the group
- options.concurrency: Maximum concurrent tasks (default: Infinity)
- Returns: Promise that resolves with body result or rejects with GroupError
Behavior: Tasks spawned via spawn() run concurrently. On first failure or external abort, all tasks receive an abort signal. The scope waits for all tasks to settle before resolving or rejecting.
Spawn<T>
Type for the spawn function: <T>(fn: (signal: AbortSignal) => Promise<T>) => Promise<T>
GroupError
Extends AggregateError. Collects errors from all failed tasks. Includes a primaryError getter for the first non-AbortError.
GroupOptions
Configuration interface for the husbandry group.
Non-goals
Husbandry intentionally does NOT provide:
- Forced task termination: Tasks must cooperatively observe the signal (cannot force-kill promises in JS)
- Retries: Compose with retry logic separately
- Timeouts: Use
AbortSignal.timeout()or compose with timeout promises - Worker pools: Use dedicated worker pool libraries for heavy CPU work
- Result streaming: Return arrays or objects from the body function
TypeScript
Full TypeScript support with strict mode. All exports are properly typed:
import husbandry, { type GroupOptions, GroupError } from "husbandry";
async function example(): Promise<string[]> {
return await husbandry(async (spawn) => {
const results = await Promise.all([
spawn(() => Promise.resolve("one")),
spawn(() => Promise.resolve("two"))
]);
return results;
});
}Related Packages
Caching & Concurrency:
- @azghr/filterkit — Framework-agnostic, type-safe filtering for TypeScript
- @azghr/singlet — Deduplicate concurrent async calls
- staleness — Stale-while-revalidate caching for async functions
Text Processing:
- @azghr/shorn — Truncate strings by byte budget without breaking graphemes
- seriatim — Sequential processing utilities
HTTP & Network:
- forbear — Read server rate-limit instructions from HTTP responses
- forestall — Delay execution until a condition is met
- obviate — Render operations unnecessary through caching
System & Process:
- quiesce — Ordered, timeboxed graceful shutdown for Node
- sortition — Deterministic percentage rollouts and A/B bucketing
- stanch — Stop flows or operations based on conditions
Utilities:
- expunge — Remove or exclude items from collections
- occlude — Hide or mask data and functionality
- placemark — Geographic location and mapping utilities
- specie — Currency and financial calculations
License
MIT
