3
\$\begingroup\$

I wrote a helper to limit Q promise concurrency.
If I have a promise-returning function promiseSomething, writing

promiseSomething = PromiseScheduler.limitConcurrency(promiseSomething, 5);

ensures no more than 5 promises are pending at the same time.

I'm coming to JS from .NET world, and I welcome critique of this code.
It seems to work fine, but I wonder if it can be made shorter / more concise / plain better.

One of the thing worth remembering is that Q always schedules continuations on the next tick.

'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
};
asked Jan 4, 2014 at 20:38
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Your code looks good to me. Promises/A are a great pattern - however it can be hard to grasp in the beginning, I personally still got problems in understanding the Q library and Promises/A spec to wrap my head around

Your implementation looks familiar to control flow patterns presented here: http://book.mixu.net/node/ch7.html

Here is another nice presentation on Promises and control flow issues: http://trevorburnham.com/presentations/flow-control-with-promises/#/

and here is a list of other Promise/A spec implementations:

JQuery

Promises/A+

answered Feb 1, 2014 at 17:28
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.