HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Limiting Q promise concurrency in JavaScript

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
concurrencyjavascriptlimitingpromise

Problem

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
};

Solution

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

  • http://api.jquery.com/promise The #1 choice in jQuery-land



Promises/A+

  • http://github.com/kriskowal/ The #1 choice in Node-land



  • http://github.com/tildeio/rsvp.js The most lightweight choice



  • http://github.com/cujojs/when The speediest choice



  • http://github.com/promises-aplus/promises-spec/blob/master/implementations.md

Context

StackExchange Code Review Q#38588, answer score: 3

Revisions (0)

No revisions yet.