Last active
August 4, 2023 15:41
-
-
Save feliperohdee/60cfec5a36991efb7df56c6b7dc75637 to your computer and use it in GitHub Desktop.
process async items with concurrency
This file contains hidden or 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 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