Skip to content

Instantly share code, notes, and snippets.

@johnwahba
Created December 23, 2023 02:27
Show Gist options
  • Save johnwahba/5f229e7f2f46439f1596f73406cbcdbf to your computer and use it in GitHub Desktop.
Save johnwahba/5f229e7f2f46439f1596f73406cbcdbf to your computer and use it in GitHub Desktop.
worker pattern nodejs
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