title: Wait for an event to happen before sending HTTP response in NodeJS?
body: <p>I'm looking for a solution to waiting for an event to happen before sending a HTTP response.</p>
  
  <p><strong>Use Case</strong></p>
  
  <ol>
  <li>The idea is I call a function in one of my routes: <code>zwave.connect("/dev/ttyACM5");</code> This function return immediately.</li>
  <li>But there exists 2 events that notice about if it succeed or fail to connect the device:</li>
  </ol>
  
  <pre class="lang-js prettyprint-override"><code>zwave.on('driver ready', function(){...});
  zwave.on('driver failed', function(){...});
  </code></pre>
  
  <ol start="3">
  <li>In my route, I would like to know if the device succeed or fail to connect before sending the HTTP response.</li>
  </ol>
  
  <p><strong>My "solution"</strong></p>
  
  <ol>
  <li>When an event happen, I save the event in a database:</li>
  </ol>
  
  <pre class="lang-js prettyprint-override"><code>zwave.on('driver ready', function(){
      //In the database, save the fact the event happened, here it's event "CONNECTED"
  });
  </code></pre>
  
  <ol start="2">
  <li>In my route, execute the connect function and wait for the event to
  appear in the database:</li>
  </ol>
  
  <pre class="lang-js prettyprint-override"><code>router.get('/', function(request, response, next) {     
      zwave.connect("/dev/ttyACM5");
      waitForEvent("CONNECTED", 5, null, function(){
          response.redirect(/connected);
      });
  });
  
  // The function use to wait for the event
  waitForEvent: function(eventType, nbCallMax, nbCall, callback){
      if(nbCall == null) nbCall = 1;
      if(nbCallMax == null) nbCallMax = 1;
  
      // Looking for event to happen (return true if event happened, false otherwise
      event = findEventInDataBase(eventType);
  
      if(event){
          waitForEvent(eventType, nbCallMax, nbCall, callback);
      }else{
          setTimeout(waitForEvent(eventType, callback, nbCallMax, (nbCall+1)), 1500);
      }
  }
  </code></pre>
  
  <p>I don't think it is a good practice because it iterates calls over the database.
  So what are your opinions/suggestions about it?</p>