2016-08-02 2 views
1

를이 내 구조입니다. NodeJS가 - - 서비스 몽고 사용할 수 없습니다 내 문제를 설명하기 전에

는 서비스 : 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

요점은 백그라운드에서 실행되는 서비스를 허용하는 것입니다. 루프없이 시도 할 것입니다. – F4Ke

+1

실행이 완료되면 같은 기능을 호출합니다. –

답변

1

여기서 문제는 while(true) 루프에 있습니다. Node.js은 단일 스레드이므로 실행 루프가 차단되어 데이터베이스 호출이 실행되지 않습니다.

간단히 성공적인 실행에 동일한 기능을 무한 루프를 제거하고 전화 :

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