Created
December 23, 2023 02:27
-
-
Save johnwahba/5f229e7f2f46439f1596f73406cbcdbf to your computer and use it in GitHub Desktop.
worker pattern nodejs
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 CONCURRENCY = 5; | |
function sleep(ms) { | |
return new Promise(resolve => setTimeout(resolve, ms)); | |
} | |
const doWork = async (work) => { | |
const duration = Math.random() > 0.5 ? 1000 : 10000 | |
await sleep(duration) | |
return console.log("doing work", work) | |
} | |
const main = async () => { | |
const work = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
const workers = [] | |
for (let i = 0; i < CONCURRENCY; i++) { | |
workers.push((async () => { | |
while (work.length > 0) { | |
const job = work.pop() | |
console.log("Starting", job) | |
await doWork(job) | |
} | |
})()) | |
} | |
return Promise.all(workers) | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment