2016-08-02 81 views
1

在解释我的问题,这是我的架构:的NodeJS - 服务无法使用蒙戈 -

1 - server is running, getting request and storing data 
2 - a service - called process_runner.js - is running on a 2nd terminal 

的服务点是从我的数据库获取数据来执行某些功能。

这是服务: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无)

什么想法?

+0

如果删除了',而(真)'循环是什么?你为什么需要它? –

+0

重点是让服务tu在后台运行 我会尝试不用循环 – F4Ke

+1

当它执行完成时调用相同的函数 –

回答

1

这里的问题在于while(true)循环。 由于Node.js是单线程,你只是阻止执行循环,它不允许你的数据库调用被执行。一旦成功执行

只需删除无限循环,并调用相同的功能:

var run = function() { 
    Capacity.find({} , function(err, capacities) { 
    //do stuff 
    return run(); 
    }); 
}