2016-10-27 7 views
1
count=0; 

    setInterval(function(){ 
    sequelize 
     .authenticate() 
     .then(function() { 
     count = count +1; 
     console.log(count.toString()); 
     socket.emit("cloud_database_status", "online"); 
     }, function() { 
     socket.emit("cloud_database_status", "offline"); 
    }); 
    },2000); 

이 코드 세트는 node.js 파일에 있습니다. 콘솔 타이머를 실행할 때 가끔 제대로 작동하지 않습니다. 코드를 처음 실행했을 때 매 2 초마다 카운트 1이 증가했습니다. 내가 멈 췄고 다시 뛰었을 때 무작위로 1 초에 몇 번씩 몇 초에 몇 초에 3 초에 몇 번씩 증가하기 시작했습니다. 1 --- 1 초 지연, 2 ---- 1 초 지연, 3 ---- 2 초 지연, 4 --- 3 초 지연. 내 코드가 뭐가 잘못 됐어? 이 비동기이기의 때문에 그것을 완료하고 때nodejs 타이머가 작동하지 않습니다.

답변

0

, 당신은 프로세스에 대한 제어 할했습니다 등

Sequelize가 자동으로 수행 할 때 dB로 연결

:

var sequelize = new Sequelize('connection string'); 

authenticate 확인 단순히 SELECT 1+1 AS result을한다 약속대로 돌아 오는 연결로 괜찮 으면.

따라서 약속에는 err이 표시됩니다. 이는 연결에 문제가 있음을 나타냅니다.

de-synchronization의 문제는 네트워크, 데이터베이스 성능/비즈니스 및 기타 여러 요인이 될 수 있습니다. 당신이 스케줄링을 통제 할 필요가 있음을 피하기 위해서.

그래서 간단하게이 작업을 수행 :

var async = require('async'); // npm i --save async 

// creating custom object in sequelize object to track connection 
sequelize.databaseConnectionStatus = { 
    connected: true, 
    status: 'online', 
    lastError: '' 
}; 
async 
    .forever(function(next) { 
    sequelize 
     .authenticate() 
     .then(function(err) { 
     sequelize.databaseConnectionStatus.connected = (err) ? false : true; 
     sequelize.databaseConnectionStatus.status = (err) ? 'offline' : 'online'; 
     sequelize.databaseConnectionStatus.lastError = err; 
     if(err) console.error(err); 

     setTimeout(next, 5000); // running check every 5 seconds 
     }); 
    }); 

var count=0; 
setInterval(function() { // independent loop to read connection status and emit by socket 
    count++; 
    socket.emit("cloud_database_status", sequelize.databaseConnectionStatus.status); 
}, 2000); 
관련 문제