2016-08-02 78 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(); 
    }); 
}