For some special cases, like 'require' it makes sense to block the execution, to make things simpler.
I have a similar case, I need a way to make DB connection, blocked. And, because it happens only one time - when the app started and saved in global object for later reuse - it will not affect the performance.
The problems:
- node doesn't have the 'sleep' method.
- there's some trickery with event loop, You has to block it, but at the same time allow to process it the database connection stuff.
Actually I already did it, by using waitFor from jasmine-node, but when I looked at it source - it's very complicated and uses phantomjs C-extensions.
And sadly, simple while(true){...} stuff doesn't works. For example, code below doesn't work, I believe because it blocks the event loop and doesn't allow node to process the event it waits for (sort of deadlock in single-threaded environment :) ).
waitsFor = (fun, message = "waitsFor timeout!", timeout = 1000) ->
start = new Date().getTime()
while true
if fun()
break
else if (new Date().getTime() - start) > timeout
throw new Error(message)
But, maybe it's somehow possible to do it in some other simple way, without extra dependencies like phantomjs and complicated C-extensions?
db.connect(function (err) { ... start app here ... });