Lee
Lee

Reputation: 3012

node.js express - delayed start

I'm using express for my http server. I want to initialize the database connection first before I start to accept any http connection from client side. Some part of the code is as below.

function connect_to_db(connection_string) {...};

connect_to_db(connection_string);
var server = app.listen(app.get('port'), function() {
    debug('Express server listening on port ' + server.address().port);
});

This doesn't work because the db connection takes time to be established. Before the connect_to_db is completed, the http server has already been started.

Any advice on how to make the code wait for the db connection to be established first?

Upvotes: 0

Views: 413

Answers (1)

Adeel
Adeel

Reputation: 19228

you need to initialize server, when you can able to connect to database. You probably need some callback, when you are connected to database. e.g.

connect_to_db(connection_string, function(){
  var server = app.listen(app.get('port'), function() {
      debug('Express server listening on port ' + server.address().port);
  });
}

Upvotes: 2

Related Questions