↑ Usage Guide Index | ← Core API OVERVIEW
Coordinate multiple HTTP requests with IDs, optional per‑item handlers, shared context, and simple success/failure semantics.
BatchLoader powers patterns like “load config + locale + feature flags, then start the app,” and is exposed at
net.batch.
BatchLoader accepts a list of jobs ({ id, method, url, handler, opts }), executes them with concurrency control, stores results in an internal context map, and signals completion through a lightweight SyncLoader controller. Only a handler that returns false marks a request as failed; everything else is treated as success.
Binds to the provided net instance and prepares defaults.
-
Parameters
net(Net) — The parent network hub; must exposehttp.get/post.fetch(object, optional) — Default HTTP options merged into each request (e.g.,{ format: 'full' }).batch(function | false, optional) — Custom batch handler.falseselects the no‑op behavior; otherwise omitted ⇒ built‑inbatchStatus(see below).
-
Properties
context: Record<string, any>— Stores per‑ID results (unless suppressed by a custom handler).fetchOpts: object— Default fetch options.batchHandler: function— Function factory used to wrap per‑item handlers.
Batch behavior is defined by a handler factory that wraps your per‑item handler(res):
batchStatus(obj, id, handler)(default) — Stores the result atcontext[id]. If!res.ok, returnsfalseto signal failure. If a per‑itemhandleris provided, its return value is used.batchStore(obj, id, handler)— Always stores the result and treats it as success unless yourhandlerreturnsfalse.batchNone(obj, id, handler)— Does not store anything automatically; you are responsible for storing and for returningfalseto signal failure.
Note: In all modes, only a returned
falsemarks the item failed. If your endpoint legitimately returns a booleanfalsebody, wrap it (e.g., use{ format: 'full' }and inspectres.body).
Submits the batch and returns a SyncLoader plus either a results map or an array of Promises (if not awaiting all).
-
loadList(Array) — Each item:{ id: "config", // required unique ID method: "get" | "post", // optional; defaults to "get" and validated url: "/config.json", // required handler: (res) => any, // optional per-item handler opts: { format: "full" }, // optional http opts merged with ctor defaults // post only data: any // body passed when method === 'post' }
-
onLoad(Function | Array | null) — Called after all required IDs resolve successfully (or whenfailis not provided). Signature:(prepend, data)whereprependincludes{ context, trigger, controller }. -
onFail(Function | Array | null) — Called if any item handler returnsfalse. -
awaitAll(boolean) —true(default): resolves to{ sync, results }whereresultsis a map{ id → last handler result }.false: resolves to{ sync, results }whereresultsis an array of live Promises submitted in order; pollsyncfor completion.
-
limit(number) — Concurrency cap for in‑flight HTTP requests. -
Returns
Promise<{ sync: SyncLoader, results: Record<string, any> | Promise<any>[] }>
-
Behavior
- Validates items (
id,url, supportedmethod, no duplicate IDs). - Builds merged opts:
{ format: 'full', ...fetchOpts, ...item.opts }. - Schedules requests via a concurrency limiter (
limit). - Wraps each response with
SyncLoader.wrapper(id, batchWrapper(...)). - Invokes
onLoadoronFailonce all required IDs are set/failed.
- Validates items (
context[id]stores per‑item results by default (mode‑dependent).get(id)returns the stored value for thatid(when using a storing batch mode).
- Validation — Missing
id/url, duplicate IDs, or unsupported methods throw immediately. - Per‑item failure — Only a handler that returns
falsemarks failure. - Network/HTTP errors — Surface from the HTTP layer; with
format: 'full', you can inspectres.ok,status, andbodyinside your handler.
const list = [
{ id: 'cfg', url: '/cfg.json' },
{ id: 'langs', url: '/i18n/en.json' }
];
const { sync, results } = await net.batch.run(list, (prepend) => {
console.log('ready', prepend.context);
});await net.batch.run([
{ id: 'cfg', url: '/cfg.json', opts: { format: 'full' }, handler: (res) => {
if (!res.ok) return false; // marks failure
return res.body?.config; // store derived value
}}
]);const { sync, results: promises } = await net.batch.run(
[{ id: 'slow', url: '/big.json' }],
null,
null,
{ awaitAll: false }
);
// Later — check completion
if (sync.loaded()) {
console.log('done, ok?', sync.success());
}net.batch.setBatchHandler(net.batch.batchStore);
await net.batch.run([{ id: 'html', url: '/page.html', opts: { format: 'full' } }]);
const page = net.batch.get('html');await net.batch.run([
{ id: 'token', method: 'post', url: '/oauth/token', data: { grant_type: 'client_credentials' },
opts: { urlencoded: true, format: 'full' } }
]);class BatchLoader {
constructor(net: Net, opts?: { fetch?: object; batch?: Function | false });
setFetchOpts(opts: object): void;
setBatchHandler(fn: Function | false): void;
get(id: string): any;
run(
loadList: Array<{ id: string; method?: 'get'|'post'; url: string; handler?: (res:any)=>any; opts?: object; data?: any }>,
onLoad?: Function | null,
onFail?: Function | null,
options?: { awaitAll?: boolean; limit?: number }
): Promise<{ sync: SyncLoader, results: Record<string, any> | Promise<any>[] }>;
}- CORE_API_HTTP.md — request/response formats used inside item handlers.
- CORE_API_SYNC_LOADER.md — controller semantics (
loaded(),failed(),success(),wrapper()). - src/batch/customBatchHandlers.md — writing your own batch handler.