Home > @rushstack/node-core-library > Async > forEachAsync
Async.forEachAsync() method
Given an input array and a callback function, invoke the callback to start a promise for each element in the array.
Signature:
static forEachAsync<TEntry extends IWeighted>(iterable: Iterable<TEntry> | AsyncIterable<TEntry>, callback: (entry: TEntry, arrayIndex: number) => Promise<void>, options: IAsyncParallelismOptions & {
weighted: true;
}): Promise<void>;
Parameters
Parameter | Type | Description |
|---|---|---|
iterable | Iterable<TEntry> | AsyncIterable<TEntry> | the array of inputs for the callback function |
callback | (entry: TEntry, arrayIndex: number) => Promise<void> | a function that starts an asynchronous promise for an element from the array |
options | IAsyncParallelismOptions & { weighted: true; } | options for customizing the control flow |
Returns:
Promise<void>
Remarks
This API is similar to the other Array#forEachAsync, except that each item can have a weight that determines how many concurrent operations are allowed. The unweighted Array#forEachAsync is a special case of this method where weight = 1 for all items.
The maximum number of concurrent operations can still be throttled using IAsyncParallelismOptions.concurrency, however it no longer determines the maximum number of operations that can be in progress at once. Instead, it determines the number of concurrency units that can be in progress at once. The weight of each operation determines how many concurrency units it takes up. For example, if the concurrency is 2 and the first operation has a weight of 2, then only one more operation can be in progress. Operations may exceed the concurrency limit based on the allowOversubscription option.
If callback throws a synchronous exception, or if it returns a promise that rejects, then the loop stops immediately. Any remaining array items will be skipped, and overall operation will reject with the first error that was encountered.