Skip to content

Static Methods (resolve / reject)

AsyncLoader.resolve() and AsyncLoader.reject() create preset-settled instances — similar to Promise.resolve / Promise.reject. The internal signal is already settled, so get() never triggers any loading.

Creating preset instances

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

// Create an already-fulfilled instance
const ok = AsyncLoader.resolve("data");
console.log(ok.isFulfilled()); // true
console.log(ok.result); // 'data'

// Create an already-rejected instance
const fail = AsyncLoader.reject(new Error("boom"));
console.log(fail.isRejected()); // true
console.log(fail.error?.message); // 'boom'

get() does not trigger loading

For a preset instance, get() returns the preset result (or throws the preset error) directly — the underlying loader function is never invoked, and loading stays false:

typescript
const fail = AsyncLoader.reject(new Error("offline"));

try {
    await fail.get(); // throws Error('offline') immediately, no loading is performed
} catch (e) {
    console.log((e as Error).message); // 'offline'
}
console.log(fail.loading); // false
console.log(fail.isRejected()); // true

Difference from a "failed load"

When a normal instance fails (rejected), the next get() auto-retries (calls load() again). But an instance created by AsyncLoader.reject() is "rejected forever" — get() keeps throwing the same error and never reloads.

Instance characteristics

FeaturePreset instanceNormal instance
Initial stateisFulfilled() / isRejected()isPending() (loads immediately when autostart=true)
get()Returns preset value / throws preset errorTriggers load() (first run / stale cache / failure retry)
loadingAlways falsetrue while loading
CacheNot written; hash is emptyCached by hash
multiplexNot involved (no hash)Reusability supported

Leaving the preset state

refresh() and invalidate() clear the preset state and restore the normal loading lifecycle (the underlying loader is called again):

typescript
const fail = AsyncLoader.reject(new Error("boom"));
// Once the underlying loader can provide real data, refresh clears the preset state and reloads
await fail.refresh(); // calls the underlying loader again

When to use

  • Default / placeholder instance: the UI needs an "immediately usable loader"; call refresh() later to fetch real data.
  • Fallback value: serve as a terminal fallback (e.g. AsyncLoader.resolve(defaultData) provides guaranteed data in an orchestration).
  • Test mocks: replace real loading in unit tests to assert how downstream code handles success / failure results.

Released under the MIT License.