Created
June 22, 2024 22:18
-
-
Save sharno/297feee13fc4ba642366f0801eb9f625 to your computer and use it in GitHub Desktop.
TS promises processing pool
This file contains 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 characters
const processInPool = async ( | |
tasks: (() => Promise<unknown>)[], | |
poolSize: number, | |
) => { | |
const pool = tasks.toReversed(); | |
const worker = async () => { | |
while (true) { | |
const task = pool.pop(); | |
if (task == null) { | |
return; | |
} | |
await task(); | |
} | |
}; | |
const workers = Array.from({ length: poolSize }, () => worker()); | |
return Promise.allSettled(workers); | |
}; | |
// Test | |
const action = (id: number) => { | |
const { promise, resolve } = Promise.withResolvers(); | |
console.log("action", id); | |
setTimeout(resolve, 2000 * Math.random()); | |
return promise; | |
}; | |
const tasks = Array.from({ length: 100 }, (_, i) => () => action(i)); | |
processInPool(tasks, 10); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment