Alex Craft
Alex Craft

Reputation: 15336

Connecting to a Database in Node.JS

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?

Upvotes: 2

Views: 572

Answers (1)

maerics
maerics

Reputation: 156424

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...
});

Upvotes: 4

Related Questions