Created
July 19, 2024 12:31
-
-
Save WKBae/2cc4075e92eb3f79c1d3e2a7049ef312 to your computer and use it in GitHub Desktop.
JS Async Semaphore / Limit 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
function semaphore(n) { | |
let running = 0; | |
const queue = []; | |
return (fn) => { | |
return new Promise((resolve) => { | |
const task = () => { | |
running++; | |
resolve( | |
fn().finally(() => { | |
running--; | |
if (queue.length > 0) { | |
queue.shift()(); | |
} | |
}), | |
); | |
}; | |
if (running < n) { | |
task(); | |
} else { | |
queue.push(task); | |
} | |
}); | |
}; | |
} | |
// Example: | |
const sem = semaphore(3); | |
function sleep(ms) { | |
return new Promise((resolve) => setTimeout(resolve, ms)); | |
} | |
sem(() => sleep(3000)).then(() => console.log("Task 1 done")); | |
sem(() => sleep(3000)).then(() => console.log("Task 2 done")); | |
sem(() => sleep(3000)).then(() => console.log("Task 3 done")); | |
sem(() => sleep(3000)).then(() => console.log("Task 4 done")); | |
sem(() => sleep(3000)).then(() => console.log("Task 5 done")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment