Skip to content

Quick Start

AsyncLoader is an async data loader built on top of AsyncSignal, encapsulating capabilities including loading + caching + abort + timeout + retry + multiplexing + error fallback + multi-loader — where multi-loader supports fallback failover (auto-switch to a backup source on primary failure) and combine multi-source merge (concurrent loads aggregated into one result). The loader function receives a merged abort signal via args.abortSignal, which can be passed directly to fetch's signal option.

Minimal example

The first constructor argument is the underlying loader function:

typescript
import { AsyncLoader } from "asyncsignal/loader";

// The first constructor argument is the underlying loader function
const loader = new AsyncLoader(async (args) => {
    const r = await fetch("/api/data", { signal: args.abortSignal });
    return await r.json();
});

const data = await loader.get(); // get the result (returns cached value if fresh)
loader.abort(); // abort loading

AsyncLoader must be imported from the subpath asyncsignal/loader (this entry includes all modules: asyncSignal + AsyncLoader; the package is marked sideEffects: false, so unused parts are tree-shaken). The main entry asyncsignal includes only the asyncSignal signal part:

typescript
import { AsyncLoader } from "asyncsignal/loader";

Core capabilities

  • Auto / lazy loading: autostart defaults to true (load on construction); set to false to trigger on first get()
  • Caching: When cache>0, results are cached by hash; get() auto-reloads after expiry
  • Abort: abort() penetrates to the underlying request via the internal signal
  • Per-attempt timeout: timeout>0 sets a timeout for each attempt; a timeout counts as a retryable failure
  • Auto retry: retry>0 auto-retries on timeout and business errors; manual abort does not retry
  • Multiplexing: reuse loader instances by hash
  • Error fallback: defaultValue swallows the final failure and resolves a fallback value
  • Sync loading: the underlying loader may return Promise<T> or a synchronous value T
  • Multi-loader: pass a loader array; orchestrate via multiLoaderStrategy as fallback failover or combine multi-source merge
  • Static factories: AsyncLoader.resolve(value) / AsyncLoader.reject(error) create preset-settled instances (no loading triggered)
  • Loading status: isPending() / isFulfilled() / isRejected()

Next steps

Released under the MIT License.