2016-04-16 110 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