2016-04-16 112 views
-1

我想从MySQL数据库获取数据和我使用的Node.js与SQL它,这是我的服务器代码:的Node.js - SQL函数没有返回值

var app = require('express')(); 
var http = require('http').Server(app); 
var io = require('socket.io')(http); 
var mysql = require('mysql'); 

var connection = mysql.createConnection({ 
    host  : '127.0.0.1', 
    user  : 'root', 
    password : '', 
    database : 'temp' 
}); 

function getData(res){ 
    var tempVal = 1377; 
    connection.connect(); 
    connection.query('SELECT * FROM tempvalues ORDER BY datetime DESC LIMIT 1', function(err, rows){ 
     console.log(rows); 
     tempVal = rows; 
    }); 
    connection.end(); 
    return tempVal; 
} 

app.get('/', function(req, res){ 
    res.sendfile('index.html'); 
}); 

io.on('connection', function(socket){ 
    socket.on('clientSent', function(data){ 
     if(data == "GET") 
      socket.emit("serverSent", getData()); 
    }) 
}) 

http.listen(3000, function(){ 
    console.log('listening on *:3000'); 
}); 

如果我去localhost:3000我只收到1377作为值,但不是来自数据库的实际值,即使控制台打印了正确的值。这是为什么?

回答

2

你的代码有一些不好的地方。 首先。认为对数据库的查询在大多数情况下是异步的。

您的代码解释:

function getData(res){ 
    var tempVal = 1377; // Create tempVal with 1377 as value initially. 
    connection.connect(); // Connect to the database. 
    // Run the query 
    connection.query('SELECT * FROM tempvalues ORDER BY datetime DESC LIMIT 1', function(err, rows){ 
     // Here you are inside the callback executed asynchronously. 
     console.log(rows); 
     // You modify the top-level variable. 
     tempVal = rows; 
    }); 
    connection.end(); // End connection 
    return tempVal; // You return 1377 since the callback is not yet finish and the value of tempVal not changed 
} 

的一个简单方法与异步代码打的回调。让你的getData函数看起来像:

function getData(callback){ 
    var tempVal = 1377; 
    connection.connect(); 
    connection.query('SELECT * FROM tempvalues ORDER BY datetime DESC LIMIT 1', function(err, rows){ 
     console.log(rows); 
     return callback(err, rows); 
    }); 
    connection.end(); 
} 

然后使用功能如下:

io.on('connection', function(socket){ 
    socket.on('clientSent', function(data){ 
     if(data == "GET") 
      getData(function(error, result){ 
       if(!error) socket.emit("serverSent", result); 
      }); 
    }) 
}); 
+0

谢谢!这工作:) – binaryBigInt