Skip to content

Instantly share code, notes, and snippets.

@AimWhy
Last active March 10, 2025 07:57
Show Gist options
  • Save AimWhy/9eac11f32bbd63293fc35b8ff7c0f842 to your computer and use it in GitHub Desktop.
Save AimWhy/9eac11f32bbd63293fc35b8ff7c0f842 to your computer and use it in GitHub Desktop.
const workerPool = (concurrentCount) => {
const queue = [];
let max = Math.max(concurrentCount, 1);
const resetMax = (m) => {
max = Math.max(m, 1);
checkQueue();
};
const checkQueue = () => {
let len = Math.min(max, queue.length);
while (len && !queue[len - 1].isRunning) {
startItem(queue[len - 1]);
}
};
const startItem = (item) => {
item.isRunning = true;
item.workFn().then(item.resolve).catch(item.reject).finally(() => {
const index = queue.indexOf(item);
queue.splice(index, 1);
checkQueue();
});
};
const runWork = (workFn) => {
const item = {
workFn,
isRunning: false,
...Promise.withResolvers()
}
queue.push(item);
checkQueue();
return item.promise;
};
return {
runWork,
resetMax,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment