我正在尝试创建一个nodejs服务器,但以下代码没有提供任何建议?
var app = require('http').createServer();
var io = require('socket.io')(app);
var mysql = require('mysql');
var dblists = new Array();
pool=mysql.createPool({host : host,user : user,password: pass });
pool.getConnection(function(err, connection){
connection.query("use nodejs");
connection.query('SELECT db_name,domain_name FROM tbl_dblist;',
function (err, rows,f) {
rows.forEach(function (entry) {
dblists[entry["domain_name"]] = entry["db_name"];
});
});
});
console.log(dblists);
提前致谢] 整个代码:
var dblists = new Array();
app.listen(3000);
var xsocket = io.listen(app);
//console.log('Listen On Port 3000');
var pool=mysql.createPool({host : host,user : user,password: pass });
pool.getConnection(function(err, connection){
connection.query("use nodejs");
connection.query('SELECT db_name,domain_name FROM tbl_dblist;',
function (err, rows,f) {
rows.forEach(function (entry) {
dblists[entry["domain_name"]] = entry["db_name"];
});
});
});
xsocket.set('authorization', function (handshakeData, callback) {
callback(null, true);
});
xsocket.on('connection', function (conn) {
xsocket.emit('list',dblists);
});
答案 0 :(得分:0)
getConnection
是异步的,因此您的console.log
会在您获得数组中的任何值之前触发。
如果将console.log
放在方法中,它将作为epxected:
xsocket.on('connection', function (conn) {
pool.getConnection(function(err, connection){
connection.query("use nodejs");
connection.query('SELECT db_name,domain_name FROM tbl_dblist;',
function (err, rows,f) {
rows.forEach(function (entry) {
dblists[entry["domain_name"]] = entry["db_name"];
});
xsocket.emit('list', dblists);
});
});
});