title: Using JS promises/generator to implement simple semaphore
body: <p>I'm trying to use NodeJS to allow only 2 tasks to access a piece of code concurrently (this could be for example accessing an API but is simulated below with the <code>yield wait(2000)</code>. I'm using the <code>co</code> package to make it work with generators and promises rather than callbacks, but the code below is only allowing 1 at a time instead of 2 to access the code between <code>yield semPromise(sem)</code> and <code>sem.leave()</code>.</p>
  
  <p>The semaphore package is the NodeJS one (<a href="https://www.npmjs.com/package/semaphore" rel="nofollow">https://www.npmjs.com/package/semaphore</a>) and has a <code>take</code> and <code>leave</code> function to enter and leave the guarded code section.</p>
  
  <p>I'm trying it with ES6 Promises below.</p>
  
  <pre><code>var sem = require('semaphore')(2);
  
  function wait(millis) {
      return new Promise(function(resolve, reject) {
          setTimeout(function(){resolve()}, millis);
      });
  }
  
  function semPromise(sem) {
      return new Promise(function(resolve, reject) {
          sem.take(function() {
              resolve();
          });
      });
  }
  
  co(function *main() {
      for (var i=0; i&lt;10; ++i) {
          yield semPromise(sem);
          console.log('enter' + i);
          yield wait(2000);
          console.log('done' + i);
          sem.leave();
      }
  });
  </code></pre>
  
  <p>But if I replace </p>
  
  <pre><code>        yield wait(2000);
          console.log('done' + i);
          sem.leave();
  </code></pre>
  
  <p>With</p>
  
  <pre><code>        setTimeout(function() {
              console.log('done');
              sem.leave();
          }, 2000);
  </code></pre>
  
  <p>It seems to work. But if I'm trying to avoid callbacks and learn how to use Promises correctly, how can I do it?</p>