NodeJS – 服务不能使用mongo –
在解释我的问题之前,这是我的架构:
1 - server is running, getting request and storing data 2 - a service - called process_runner.js - is running on a 2nd terminal
该服务的重点是从我的数据库获取数据执行一些function。
这是服务: process_runner.js
// all needed requires /// ... // mongoose.connect(config.database); var db = mongoose.connection; db.on('error', console.error.bind(console, 'Error connecting to MongoDB:')); db.once('open', function() { console.log("Connected to MongoDB"); try { run(); } catch (e) { console.log (e); } }); //... var run = function() { console.log("Start processes manager"); var taken = false; while(true) { console.log ("iteration") if (taken == false) { taken = true; console.log("go"); // Then I want to get my capacities // when the call below is done, nothing appends and the loop continues Capacity.find({} , function(err, capacities) { console.log ("OK CONTINUE"); // ... // next of the events }); ... }...
(循环有sleep(1)
)
这是输出:
Connected to MongoDB Start processes manager iteration go iteration iteration iteration ...
所以,在“发送”消息之后,我需要收到“OK CONTINUE”消息,其余的代码将会执行,
但是当Capacity.find({} , function(err, capacities) {....
)完成时,没有任何附加操作并且循环继续( err
没有任何内容)
有任何想法吗 ?
这里的问题在于while(true)
循环。 由于Node.js
是单线程的,所以你只是阻止了执行循环,这不允许你的数据库调用被执行。
只需删除无限循环,并成功执行时调用相同的function:
var run = function() { Capacity.find({} , function(err, capacities) { //do stuff return run(); }); }