@chriscdn/async-each
v3.0.0
Published
Iterate an array in an asynchronous manner.
Maintainers
Readme
@chriscdn/async-each
Asynchronously iterate over an array with optional concurrency control and a progress callback.
Installation
Using npm:
npm install @chriscdn/async-eachUsing yarn:
yarn add @chriscdn/async-eachMotivation
Processing large arrays synchronously can block the event loop and make the UI unresponsive.
@chriscdn/async-each provides an asynchronous iteration method with optional concurrency control and progress reporting, returning a Promise that resolves to an array of results in the same order as the input.
API
asyncEach<T, R>(items, callbackFn, statusCallbackFn?, options?) => Promise<R[]>
Iterate over an array asynchronously.
Parameters
items: Array<T>Array of items to process.callbackFn: (item: T, index: number, items: Array<T>) => R | Promise<R>Function executed for each item. Can return a value or a promise. Arguments:item– Current item being processedindex– Zero-based index of the itemitems– Full array being processed
statusCallbackFn?: (status: AsyncEachStatus<T, R>) => voidOptional callback invoked after each item completes. Receives a status object:progress– Number of items processed so fartotal– Total number of itemspercent– Completion percentage (integer 0–100)item– The item just processedindex– Index of the itemresult– Value returned or resolved bycallbackFnfor this item
options?: { rateLimit?: number }Optional configuration:rateLimit– Maximum number of concurrent operations (default0for unlimited concurrency)
Returns
Promise<R[]> – Resolves to an array of results in the same order as the input array. Rejects if any callback fails.
Types
export type AsyncEachStatus<T, R> = {
progress: number;
total: number;
percent: number;
item: T;
index: number;
result: R;
};Example
import { asyncEach } from "@chriscdn/async-each";
// Assume fetchUserData performs an async API call to return user info
const users = ["alice", "bob", "charlie", "dave"];
const results = await asyncEach(
users,
async (username) => fetchUserData(username),
(status) => {
console.log(
`Processed ${status.progress}/${status.total} (${status.percent}%)`,
status.result,
);
},
{ rateLimit: 2 }, // only 2 requests at a time
);
console.log("All users fetched:", results);