2

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:

  1. node doesn't have the 'sleep' method.
  2. 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?

2
  • Why not just wait to start the app until your database connection is established? db.connect(function (err) { ... start app here ... }); Commented Jan 10, 2012 at 17:57
  • 3
    "saved in global object for later reuse" does not sound good. Commented Jan 10, 2012 at 18:00

1 Answer 1

4

Your application should first attempt to connect to the database asynchronously and then proceed with its processing logic when the connection is available. For example:

db.connect(function(conn, err) {
  if (err) throw err;
  // Put your program logic using the db connection here...
});
Sign up to request clarification or add additional context in comments.

1 Comment

+1, it appears the OP is trying to use NodeJS in a manner that it was explicitly not intended to be used in. Any normally long blocking calls should be done asynchronously (DB access, file access, etc.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.