Node.js - SQL 函数没有 return 值

Node.js - SQL function doesn't return value

我想从 MySQL 数据库获取数据,我使用 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 作为值,而不是数据库中的实际值,即使控制台打印出正确的值。这是为什么?

您的代码中有些问题。 第一的。认为对数据库的查询,在大多数情况下是异步的。

您的代码解释:

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