title: Limit concurrency of promise being run
body: <p>I'm looking for a promise function wrapper that can limit / throttle when a given promise is running so that only a set number of that promise is running at a given time.</p>
  
  <p>In the case below <code>delayPromise</code> should never run concurrently, they should all run one at a time in a first-come-first-serve order.</p>
  
  <pre><code>import Promise from 'bluebird'
  
  function _delayPromise (seconds, str) {
    console.log(str)
    return Promise.delay(seconds)
  }
  
  let delayPromise = limitConcurrency(_delayPromise, 1)
  
  async function a() {
    await delayPromise(100, "a:a")
    await delayPromise(100, "a:b")
    await delayPromise(100, "a:c")
  }
  
  async function b() {
    await delayPromise(100, "b:a")
    await delayPromise(100, "b:b")
    await delayPromise(100, "b:c")
  }
  
  a().then(() =&gt; console.log('done'))
  
  b().then(() =&gt; console.log('done'))
  </code></pre>
  
  <p>Any ideas on how to get a queue like this set up?</p>
  
  <p>I have a "debounce" function from the wonderful <code>Benjamin Gruenbaum</code>. I need to modify this to throttle a promise based on it's own execution and not the delay.</p>
  
  <pre><code>export function promiseDebounce (fn, delay, count) {
    let working = 0
    let queue = []
    function work () {
      if ((queue.length === 0) || (working === count)) return
      working++
      Promise.delay(delay).tap(function () { working-- }).then(work)
      var next = queue.shift()
      next[2](fn.apply(next[0], next[1]))
    }
    return function debounced () {
      var args = arguments
      return new Promise(function (resolve) {
        queue.push([this, args, resolve])
        if (working &lt; count) work()
      }.bind(this))
    }
  }
  </code></pre>