最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

我想从mysql的connection.query中取出结果,并将其保存在nodejs的全局作用域链中

IT培训 admin 4浏览 0评论

我想从mysql的connection.query中取出结果,并将其保存在nodejs的全局作用域链中

我试图通过存储在可变的当前产品中得出结果。但是我无法在函数外部使用它,因此我的数组返回空值

var connection = mysql.createConnection({
                host: config.config.mysql.opencart_local.host,
                user: config.config.mysql.opencart_local.user,
                password: config.config.mysql.opencart_local.password,
                database: config.config.mysql.opencart_local.database
                })
var query_current_products = 'select * from table;';
var current_products = [];

  connection.connect(function(err) {
                       if (err) throw err;
                       console.log("Connected!");
                       connection.query(query_current_products, function (err, result) {
                             if (err) throw err;
                             //console.log(result);
                            current_products = result;
                      });

                }
                )
console.log(current_products);

enter image description here

回答如下:
console.log(current_products);

此行将在之前执行

current_products = result;

由于javascript的异步功能。

您必须在connection.query的回调函数中执行后续操作,并且代码将难以维护,人们将其称为callback hell

或者,如果将代码包装在异步函数中并自己保证连接/查询函数的使用,或者使用promise-mysql包,则可以使用异步/等待语法。

我想从mysql的connection.query中取出结果,并将其保存在nodejs的全局作用域链中

我试图通过存储在可变的当前产品中得出结果。但是我无法在函数外部使用它,因此我的数组返回空值

var connection = mysql.createConnection({
                host: config.config.mysql.opencart_local.host,
                user: config.config.mysql.opencart_local.user,
                password: config.config.mysql.opencart_local.password,
                database: config.config.mysql.opencart_local.database
                })
var query_current_products = 'select * from table;';
var current_products = [];

  connection.connect(function(err) {
                       if (err) throw err;
                       console.log("Connected!");
                       connection.query(query_current_products, function (err, result) {
                             if (err) throw err;
                             //console.log(result);
                            current_products = result;
                      });

                }
                )
console.log(current_products);

enter image description here

回答如下:
console.log(current_products);

此行将在之前执行

current_products = result;

由于javascript的异步功能。

您必须在connection.query的回调函数中执行后续操作,并且代码将难以维护,人们将其称为callback hell

或者,如果将代码包装在异步函数中并自己保证连接/查询函数的使用,或者使用promise-mysql包,则可以使用异步/等待语法。

发布评论

评论列表 (0)

  1. 暂无评论