title: How to use asynchronous initialization in a Connect middleware?
body: <p>I wrote a middleware for Connect and Express that requires some heavy lifting in its setup method. Due to the nature of the initialization tasks this stuff is asynchronous, so I have the problem that the middleware shall only be accessible once the initialization has been run.</p>
  
  <p>Currently I have solved it using a callback:</p>
  
  <pre><code>function setupMiddleware(callback) {
    doSomeAsyncInitialization(function () {
      callback(function (req, res, next) {
        // The actual middleware goes here ...
      });
    });
  }
  </code></pre>
  
  <p>This works, but it's not nice for the caller. Instead of being able to do</p>
  
  <pre><code>app.use(setupMiddleware());
  </code></pre>
  
  <p>I have to do:</p>
  
  <pre><code>setupMiddleware(functin (middleware) {
    app.use(middleware);
  });
  </code></pre>
  
  <p>Now I was thinking whether there is a better approach, e.g. let the middleware initialize in the background and delay all incoming requests until the middleware is ready.</p>
  
  <p>How could I solve this? Any ideas or best practices that I should use here?</p>