Skip to content

Instantly share code, notes, and snippets.

@feliperohdee
Last active August 4, 2023 15:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feliperohdee/60cfec5a36991efb7df56c6b7dc75637 to your computer and use it in GitHub Desktop.
Save feliperohdee/60cfec5a36991efb7df56c6b7dc75637 to your computer and use it in GitHub Desktop.
process async items with concurrency
const worker = async (queue, concurrency = 25) => {
let index = 0;
let results = [];
let threads = [];
const execThread = async () => {
while (index < queue.length) {
const currentIndex = index++;
// Use of `currentIndex` is important because `index` may change after await is resolved
results[currentIndex] = await queue[currentIndex]();
}
};
for (let i = 0; i < concurrency; i++) {
threads.push(execThread());
}
await Promise.all(threads);
return results;
};
const items = [new Array(1000)];
const queue = items.map((item, index) => {
return async () => {
try {
console.log(`Processing item ${index}`);
return item;
} catch(err) {
return {
error: err.message
};
}
};
}
const results = await worker(queue, 25);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment