| 1 | /**
|
|---|
| 2 | * Wraps an async function to limit the number of concurrent executions.
|
|---|
| 3 | *
|
|---|
| 4 | * This function creates a wrapper around an async callback that ensures at most
|
|---|
| 5 | * `concurrency` number of executions can run simultaneously. Additional calls will
|
|---|
| 6 | * wait until a slot becomes available.
|
|---|
| 7 | *
|
|---|
| 8 | * @template F - The type of the async function to wrap.
|
|---|
| 9 | * @param {F} callback The async function to wrap with concurrency control.
|
|---|
| 10 | * @param {number} concurrency Maximum number of concurrent executions allowed.
|
|---|
| 11 | * @returns {F} A wrapped version of the callback with concurrency limiting.
|
|---|
| 12 | * @example
|
|---|
| 13 | * const limitedFetch = limitAsync(async (url) => {
|
|---|
| 14 | * return await fetch(url);
|
|---|
| 15 | * }, 3);
|
|---|
| 16 | *
|
|---|
| 17 | * // Only 3 fetches will run concurrently
|
|---|
| 18 | * const urls = ['url1', 'url2', 'url3', 'url4', 'url5'];
|
|---|
| 19 | * await Promise.all(urls.map(url => limitedFetch(url)));
|
|---|
| 20 | *
|
|---|
| 21 | * @example
|
|---|
| 22 | * const processItem = async (item) => {
|
|---|
| 23 | * // Expensive async operation
|
|---|
| 24 | * return await heavyComputation(item);
|
|---|
| 25 | * };
|
|---|
| 26 | *
|
|---|
| 27 | * const limitedProcess = limitAsync(processItem, 2);
|
|---|
| 28 | * const items = [1, 2, 3, 4, 5];
|
|---|
| 29 | * // At most 2 items will be processed concurrently
|
|---|
| 30 | * await Promise.all(items.map(item => limitedProcess(item)));
|
|---|
| 31 | */
|
|---|
| 32 | declare function limitAsync<F extends (...args: any[]) => Promise<any>>(callback: F, concurrency: number): F;
|
|---|
| 33 |
|
|---|
| 34 | export { limitAsync };
|
|---|