Skip to content

Instantly share code, notes, and snippets.

@gaearon
Last active March 29, 2018 06:12
Show Gist options
  • Save gaearon/7930162 to your computer and use it in GitHub Desktop.
Save gaearon/7930162 to your computer and use it in GitHub Desktop.
Q promise concurrency limiter
'use strict';
var q = require('q');
/**
* Constructs a function that proxies to promiseFactory
* limiting the count of promises that can run simultaneously.
* @param promiseFactory function that returns promises.
* @param limit how many promises are allowed to be running at the same time.
* @returns function that returns a promise that eventually proxies to promiseFactory.
*/
function limitConcurrency(promiseFactory, limit) {
var running = 0,
semaphore;
function scheduleNextJob() {
if (running < limit) {
running++;
return q();
}
if (!semaphore) {
semaphore = q.defer();
}
return semaphore.promise
.finally(scheduleNextJob);
}
function processScheduledJobs() {
running--;
if (semaphore && running < limit) {
semaphore.resolve();
semaphore = null;
}
}
return function () {
var _this = this,
args = arguments;
function runJob() {
return promiseFactory.apply(_this, args);
}
return scheduleNextJob()
.then(runJob)
.finally(processScheduledJobs);
};
}
module.exports = {
limitConcurrency: limitConcurrency
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment