Skip to content

Instantly share code, notes, and snippets.

@sharno
Created June 22, 2024 22:18
Show Gist options
  • Save sharno/297feee13fc4ba642366f0801eb9f625 to your computer and use it in GitHub Desktop.
Save sharno/297feee13fc4ba642366f0801eb9f625 to your computer and use it in GitHub Desktop.
TS promises processing pool
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