【问题标题】:Node.js - SQL function doesn't return valueNode.js - SQL 函数不返回值
【发布时间】:2016-08-08 11:39:27
【问题描述】:

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

【问题讨论】:

    标签: mysql sql node.js socket.io


    【解决方案1】:

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

    你的代码解释:

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

    【讨论】:

      猜你喜欢
      • 2016-08-14
      • 1970-01-01
      • 1970-01-01
      • 2016-01-03
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 2013-05-06
      • 1970-01-01
      相关资源
      最近更新 更多