Last active
July 9, 2025 10:28
-
-
Save juliendargelos/c5a3e1b54d94edcf764d841a003d0951 to your computer and use it in GitHub Desktop.
Revisions
-
juliendargelos revised this gist
Jul 9, 2025 . 1 changed file with 4 additions and 4 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -3,10 +3,10 @@ * concurrency limit. A concurrency limit equal to Infinity makes this function * behave like `Promise.all`. * * @params items - List of items to process * @params run - Asynchronous function to run for each item * @params concurrency - Maximum number of concurrent executions * @return A Promise that resolves to an array of results */ async function concurrent<Item = any, Result = any>( items: Iterable<Item>, -
juliendargelos created this gist
Jul 9, 2025 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,28 @@ /** * Concurrently run an asynchronous function on a list of items given a * concurrency limit. A concurrency limit equal to Infinity makes this function * behave like `Promise.all`. * * @params items - List of items to process. * @params run - Function to run for each item, which returns a Promise. * @params concurrency - Maximum number of concurrent executions. * @return A Promise that resolves to an array of results. */ async function concurrent<Item = any, Result = any>( items: Iterable<Item>, run: (item: Item, index: number) => Promise<Result>, concurrency: number = Infinity ): Promise<Result[]> { const pool: (() => void)[] = [] concurrency = Math.max(1, Math.floor(concurrency || 0)) return Promise.all([...items].map((item, index) => ( new Promise<Result>((resolve, reject) => { const start = () => run(item, index) .then((result) => { pool.pop()?.(), resolve(result) }) .catch((error) => { pool.splice(0), reject(error) }) index < concurrency ? start() : pool.unshift(start) }) ))) }