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.
Currently I have solved it using a callback:
function setupMiddleware(callback) {
doSomeAsyncInitialization(function () {
callback(function (req, res, next) {
// The actual middleware goes here ...
});
});
}
This works, but it's not nice for the caller. Instead of being able to do:
app.use(setupMiddleware());
I have to do:
setupMiddleware(functin (middleware) {
app.use(middleware);
});
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.
How could I solve this? Any ideas or best practices that I should use here?