Reputation: 49
I would love to know a few things about Node.js async and MongoDB. If the server starts before my connection to, and my templates or Ajax depend on data from the database will serving (I precompile my handlebars) the HTML file fail or will my templates/Ajax wait for the connection and then continue?
If it works, I would love to understand better how exactly it worked! If it fails, how can I "fix" it elegantly?
This is an example of a solution, using hoisting (seems bad to me tbh):
//connect to db
mongodb.connect("someDBplace",
(err, db)=>{
if(err){
return generalLogger.error(`The database has failed to connect: ${err}.`);
}else{ //start the server now:
generalLogger.info(`Connected to database: ${stringify(db.databaseName)}.`);
server.listen(`${port}`, (err)=>{
if(err){
generalLogger.error(err);
}
//for demo: console th eMIMEtype
generalLogger.info(`The Server started on port: ${port}.`);
});
}
});
Upvotes: 1
Views: 56
Reputation: 111434
Yes, this is a correct way to do it. If you want to make sure that the database is available before the server starts serving requests, then you need to start the server in the callback of the database connection method.
Some higher level frameworks like Hapi may provide you some mechanisms to simplify the case when you need to wait for several things before starting. For example see the Hapi plugins:
Upvotes: 1