javascript - 无法使用 mysql 和 Node js 返回选择查询值

标签 javascript mysql node.js asynccallback

我是 node js 的新手,现在我正在尝试使用 node js 在 mysql 中设置 select 查询的返回值....我正在使用 node-mysql 包...

示例代码

var mysql =  require('mysql');
var connection =  mysql.createConnection({
    host : "localhost",
    user : "root",
    password: "root123",
    database: "testdb"
});

var retValue = undefined;

var query = connection.query('SELECT * FROM tblData;');
query
    .on('error', function(err) {
        // Handle error, an 'end' event will be emitted after this as well
    })
    .on('fields', function(fields) {
        // the field packets for the rows to follow
    })
    .on('result', function(row) {
        // Pausing the connnection is useful if your processing involves I/O
        connection.pause();
        processRow(row, function() {
            retValue = row;
        });
    })
    .on('end', function(row) {

    });

    connection.end();

    function processRow(rows)
    {
        retValue = rows;
    }

    console.log(retValue);

retValue 始终未定义。我知道这是异步调用。谁能告诉我如何为这个变量设置值。

谢谢 迪帕克

最佳答案

由于数据库查询是异步操作,因此在您调用 console.log(retValue) 时您的变量 retValue 尚未设置。

var retValue;

var query = connection.query('SELECT * FROM tblData;');
query
    .on('error', function(err) {
        // Handle error, an 'end' event will be emitted after this as well
    })
    .on('fields', function(fields) {
        // the field packets for the rows to follow
    })
    .on('result', function(row) {
        // Pausing the connnection is useful if your processing involves I/O
        connection.pause();
        processRow(row);
        console.log(retValue); //retValue is now set
    })
    .on('end', function(row) {

    });

    connection.end();

    function processRow(rows)
    {
        retValue = rows;
    }

    console.log(retValue); // undefined, retValue has not been set yet

关于javascript - 无法使用 mysql 和 Node js 返回选择查询值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29913206/

相关文章:

javascript - 无法通过jquery使用php登录

javascript - 本地存储更改事件+ react

php - 如何在 YII 中使用 Sphinx 搜索?

python - 在共享服务器 : No module named MySQLdb? 上安装 Django

node.js - 使用express + webpack中间件时如何在.ejs更改时自动刷新浏览器?

javascript - 无法连接到后端,找不到我的路径/文件

javascript - 使用 GM_xmlhttpRequest 获取多个外部 URL,将页面 <H1> 添加到链接?

PHP 和 MYSQL 优化的按日期间隔选择的方式

javascript - JS : Create Objects in loop with iterator

javascript - 向我自己的 API 发送请求以更改未更新的数据库。我想更新数据库