【问题标题】:NodeJS MySQL How to get the result outside of the query functionNodeJS MySQL如何在查询函数之外获取结果
【发布时间】:2015-07-26 08:52:09
【问题描述】:

我似乎无法弄清楚如何在 NodeJS MySQL 池查询之外获得结果。这是一些示例代码,可以更好地解释我的意思。

var result = 'Hello world!';

var mysql = require('mysql');
var pool = mysql.createPool({
    connectionLimit : 100,
    host            : process.env.DB_HOST,
    user            : process.env.DB_USERNAME,
    password        : process.env.DB_PASSWORD,
    database        : process.env.DB_DATABASE
});

pool.query('SELECT * from user LIMIT 10', function (err, rows) {
    result = rows;
});

res.send(result);

上面将返回“Hello world!”而不是查询。

如果我在 pool.query 函数中使用 console.log(result),它会返回查询中的行,但我似乎无法在函数之外获取数据。我已经记录了这个函数并检查了所有相关的函数,我想我只是缺少一些基本的东西。

【问题讨论】:

标签: javascript mysql node.js express connection-pooling


【解决方案1】:

您在查询完成(并调用回调)之前将结果发回。在您的回调中发送结果将解决问题:

pool.query('SELECT * from user LIMIT 10', function (err, rows) {
    result = rows;
    res.send(result);
});

正如 Aaron 所指出的,这是一个常见问题。更全面的答案可以在here找到。

【讨论】:

    【解决方案2】:

    池查询功能是异步的。这意味着您的代码不会按照您声明语句的顺序执行。

    您启动一个查询并指定一个回调函数,该函数应在查询异步操作完成时运行。

    res.send 将在查询和回调声明之后立即运行,而回调将在很晚的时候运行。当您设置结果时,您已经发送了它。

    尝试将你的 res.send 移动到回调中。

    pool.query('SELECT * from user LIMIT 10', function (err, rows) {
        res.send(rows);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-10
      • 1970-01-01
      • 2013-07-27
      • 2019-01-02
      • 1970-01-01
      • 2021-12-31
      • 2017-04-25
      • 1970-01-01
      相关资源
      最近更新 更多