gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:32:56 25 4
gpt4 key购买 nike

我尝试通过存储在可变的当前产品中来得出结果。但我不能在函数之外使用它,所以我的数组返回空

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

最佳答案

尝试使用 async/await 语法来获取结果

  const mysql = require('mysql'); // or use import if you use TS
const util = require('util');
const conn = 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 current_products = [];
//
var query_current_products = 'select * from table;';

(async function getProducts () => {
try {
const rows = await query( query_current_products);
console.log(rows);
current_products=rows;
} finally {
conn.end();
}
})()

关于javascript - 我想从mysql的connection.query中取出结果并将其保存在nodejs的全局作用域链中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58299557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com