Skip to content

Instantly share code, notes, and snippets.

View BrenoAlberto's full-sized avatar
🦜
peace tranquility mind flowers

Breno Alberto BrenoAlberto

🦜
peace tranquility mind flowers
View GitHub Profile
@BrenoAlberto
BrenoAlberto / concurrentTaskQueue.ts
Created March 6, 2023 22:52
It takes an array of functions that return promises (asyncFunctions) and the maximum number of functions to be executed concurrently (maxConcurrent). The function will execute up to maxConcurrent functions in parallel, and once a function completes, it will start a new one until all functions have completed. The function returns a promise that r…
export async function concurrentTaskQueue<T>(asyncFunctions: Array<() => Promise<T>>, maxConcurrent: number): Promise<T[]> {
let currentIndex = 0;
const runningFunctions = new Set<Promise<T>>();
const orderedRunnedFunctions: Map<Promise<T>, number> = new Map();
let results: Array<T> = Array(asyncFunctions.length);
while (currentIndex < asyncFunctions.length) {
while (runningFunctions.size < maxConcurrent && currentIndex < asyncFunctions.length) {
const asyncFunction = asyncFunctions[currentIndex];
const promise = asyncFunction().finally(() => {
runningFunctions.delete(promise);