2016-04-16 5 views
-1

を返しませんが、これは私のサーバーのコードです:場合Node.jsのSQL関数は、私は、MySQLデータベースからデータを取得したいと私はそれのためのSQLでのNode.jsを使っ値

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'); 
}); 

I 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 
} 

非同期コードと戦うために1つの簡単な方法は、コールバックです。あなたの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

関連する問題