Nodejs setTimeout数据库问题

时间:2014-10-09 11:34:03

标签: javascript node.js

以下是我的代码部分:

var nodePort = 3030;
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var db = require('mysql');
var dbPool = db.createPool({
    host : 'localhost',
    user : 'root',
    password : '1234',
    database : 'test',
    port : 3306
});


var gcm = require('node-gcm');
var message = new gcm.Message();
var sender = new gcm.Sender('API'); //Api Key
var registrationIds = [];

app.use( bodyParser.json() );
app.use( bodyParser.urlencoded() ); 

foo = function(){
  dbPool.getConnection(function(objErr, objConn){
    if(objErr){
        console.log('ERROR');
    }else{
        objConn.query("SELECT * FROM person", function(Err, Rows, Fields){
            for(var i=0; i<Rows.length; i++){
                console.log(Rows[i].Name);
            }
        });
    }
  });
  setTimeout(foo,1000);
}
foo();
app.listen(nodePort);
console.log('App listening on port' + nodePort);

enter image description here

如果我尝试连接数据库,此功能仅运行10次并停止。
我想每秒检查一次我的数据库,有什么方法可以做到吗?

1 个答案:

答案 0 :(得分:0)

var nodePort = 3030;
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var db = require('mysql');
var dbPool = db.createPool({
    host : 'localhost',
    user : 'root',
    password : '1234',
    database : 'test',
    port : 3306
});


var gcm = require('node-gcm');
var message = new gcm.Message();
var sender = new gcm.Sender('API'); //Api Key
var registrationIds = [];

app.use( bodyParser.json() );
app.use( bodyParser.urlencoded() ); 

foo = function(){
  dbPool.getConnection(function(objErr, objConn){
    if(objErr){
        console.log('ERROR');
    }else{
        objConn.query("SELECT * FROM person", function(Err, Rows, Fields){
            for(var i=0; i<Rows.length; i++){
                console.log(Rows[i].Name);
            }
        });
    }
  });
}
setInterval(function(){foo();},1000);

app.listen(nodePort);
console.log('App listening on port' + nodePort);