title: JavaScript Scheduler implementation using promises
body: <p>I was solving this interesting javascript problem (interview question) and I got stuck on how I can implement this using promises.</p>
  
  <p><strong>Problem:</strong></p>
  
  <blockquote>
    <p>Write a scheduler in JavaScript that accepts max number of concurrent
    tasks as a parameter and schedules tasks (each task may take arbitrary
    time to complete).</p>
  </blockquote>
  
  <p>Please note that we need to only execute "n" (concurrent) tasks at a time before proceeding to execute other tasks.</p>
  
  <p>This is my implementation:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var exampleTaskA = function () {
      setTimeout(function () {
          console.log('Task A Done');
      }, 1000);
  };
  
  function TaskRunner(concurrency) {
      this.limit = concurrency;
      this.store = [];
      this.len = this.store.length;
  }
  
  TaskRunner.prototype.push = function (task) {
      this.store.push(task);
      function getWorker(store, limit) {
          if(!store.length) return;
  
          if(store.length &lt;= limit) {
              const cur = store.shift();
              if(cur) cur();
              getWorker(store, limit);
          }
      }
  
      getWorker(this.store, this.limit);
  }
  
  var task = new TaskRunner(2);
  console.log(task.push(exampleTaskA));
  console.log(task.push(exampleTaskA));
  console.log(task.push(exampleTaskA)); 
  console.log(task.push(exampleTaskA));
  console.log(task.push(exampleTaskA));
  console.log(task.push(exampleTaskA));
  console.log(task.push(exampleTaskA));</code></pre>
  </div>
  </div>
  </p>
  
  <p>How can I use promises / async await to implement this? Should I wrap everything around a promise before pushing?</p>
  
  <p>Can someone enlighten?</p>