The best way for Node JS to wait when booting for initialization from the database, e…

微信扫一扫,分享到朋友圈

The best way for Node JS to wait when booting for initialization from the database, e…

I know Node is non blocking etc but i dont know how to solve this issue without blocking.

You start the server

node app.js

but you need some config etc from a database or mongodb before you deal with incoming requests, so you need to wait for the db response to return before you launch into dealing with taking requests.

I could use nimble but then you have to wrap the routes etc all in a second execution block which is nasty.

Whats the best way?

Node is indeed non-blocking, but that doesn’t mean you need to start accepting requests right away! Take a look at the classic HTTP server example:

var http = require('http');

var server = http.createServer(function (req, res) {
 // ... logic to handle requests ...
});

server.listen(8000);

You can do anything you like before calling server.listen
, including whatever configuration tasks you need. Assuming those tasks are asynchronous, you can start the server in the callback:

var http = require('http');

var server = http.createServer(function (req, res) {
 // ... logic to handle requests ...
});

// Set up your mongo DB and grab a collection, and then...
myMongoCollection.find().toArray(function(err, results) {

   // Do something with results here...

   // Then start the server
   server.listen(8000);

});

微信扫一扫,分享到朋友圈

The best way for Node JS to wait when booting for initialization from the database, e…

俄克拉荷马州两人因盗窃1400万美元的加密货币被捕

上一篇

Preparing the fetch instruction in db2

下一篇

你也可能喜欢

The best way for Node JS to wait when booting for initialization from the database, e…

长按储存图像,分享给朋友