How to use asynchronous initialization in Connect middleware

I wrote middleware for Connect and Express that requires some heavy lifting in its setup method. Due to the nature of the initialization tasks, this material is asynchronous, so I have a problem that the middleware should only be available after starting the initialization.

Currently, I decided to use it with a callback:

function setupMiddleware(callback) { doSomeAsyncInitialization(function () { callback(function (req, res, next) { // The actual middleware goes here ... }); }); } 

It works, but it is not nice for the caller. Instead of doing

 app.use(setupMiddleware()); 

I need to do:

 setupMiddleware(functin (middleware) { app.use(middleware); }); 

Now I was wondering if there is a better approach, for example. Let the middleware initialize in the background and delay all incoming requests until the middleware is ready.

How can i solve this? Any ideas or recommendations I should use here?

+7
source share
2 answers

Now I decided to use it with the isInitialized variable and delay the middleware function. See the following example:

 var connect = require('connect'); var setup = function () { var isInitialized = false; setTimeout(function () { isInitialized = true; }, 10000); function run (req, res, next) { res.write('Foo'); res.end(); } function delay (req, res, next) { if (isInitialized) { return run(req, res, next); } setTimeout(function () { delay(req, res, next); }, 1000); } return function (req, res, next) { if (req.url === '/foo') { delay(req, res, next); return; } next(); } }; var app = connect(); app.use(setup()); app.use(function (req, res) { res.write('Fertig!'); res.end(); }); var http = require('http'); http.createServer(app).listen(5000); 

Please note that this code has not been optimized or refactored in any way, it is just a demonstration that the idea itself works.

+2
source

Why do not you do as described below

 doSomeAsyncInitialization(function () { //After doing all long running init process just configure your express as follows. app.use(<middlewares>); app.listen(<portnumder>); }); 
0
source

All Articles