How can I limit Q promise concurrency?

前端 未结 4 1297
时光取名叫无心
时光取名叫无心 2020-12-09 19:31

How do I write a method that limits Q promise concurrency?

For instance, I have a method spawnProcess. It returns a Q promise.
I want no more than 5

4条回答
  •  无人及你
    2020-12-09 19:53

    This seems to be working for me.

    I'm not sure if I could simplify it. The recursion in scheduleNextJob is necessary so the running < limit and limit++ always execute in the same tick.

    Also available as a gist.

    '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 args = arguments;
    
        function runJob() {
          return promiseFactory.apply(this, args);
        }
    
        return scheduleNextJob()
          .then(runJob)
          .finally(processScheduledJobs);
      };
    }
    
    module.exports = {
      limitConcurrency: limitConcurrency
    }
    

提交回复
热议问题