Created
November 16, 2016 10:55
-
-
Save 11bit/d03fa4b6ea2ed88ad9194613c92f6726 to your computer and use it in GitHub Desktop.
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
function ThrottledQueue(){ | |
let queue = [] | |
let runningJobs = 0 | |
function nextJob() { | |
runningJobs++ | |
setImmediate(() => { | |
if (queue.length > 0) | |
queue.pop().runJob() | |
}) | |
}) | |
function wrapJob(job) { | |
let runJob | |
let jobPromise = new Promise(resolve => { | |
runJob = resolve | |
}).then(job) | |
let wrappedJob = { | |
runJob: runJob, | |
jobPromise: jobPromise, | |
} | |
jobPromise.finally(() => { | |
runningJobs-- | |
nextJob(wrappedJob) | |
}) | |
return jobPromise | |
} | |
return { | |
push(job) { | |
let wrapped = wrapJob(job) | |
queue.push(wrapped) | |
if (runningJobs <= 5) { | |
nextJob() | |
} | |
return wrapped.jobPromise | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment