2016-04-16 12 views
-1

zurückgibt Wert Ich mag ein Datum aus einer MySQL-Datenbank erhalten und ich verwende Node.js mit SQL für sie, das ist mein Server-Code:Node.js - SQL-Funktion nicht

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

Wenn i Gehe zu localhost:3000 Ich bekomme nur 1377 als Wert, aber nicht den tatsächlichen Wert aus der Datenbank, obwohl die Konsole die richtigen Werte druckt. Warum das?

Antwort

2

In Ihrem Code sind einige Dinge schlecht. Zuerst. Stellen Sie sich vor, dass Abfragen an die Datenbank in den meisten Fällen asynchron sind.

Ihr Code erklärt:

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 
} 

Eine einfache Möglichkeit, mit Asynchron-Code zu kämpfen die Rückrufe sind. Lassen Sie Ihre getData Funktion wie folgt aussehen:

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

dann die Funktion wie folgt:

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

Dank! Das funktioniert :) – binaryBigInt