我想从mysql的connection.query中取出结果并将其保存在nodejs的全局作用域链中 [英] I want to take out the result from mysql's connection.query and save it in global scope chain in nodejs
本文介绍了我想从mysql的connection.query中取出结果并将其保存在nodejs的全局作用域链中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试通过存储在可变当前产品中来显示结果.但是我不能在函数外使用它,所以我的数组返回空
I tried bringing out result by storing in variable current product. But I cant use it outside the function, so my array returns empty
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);
推荐答案
尝试使用 async/await 语法来获得结果
Try to use async/await syntax to get your results
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();
}
})()
这篇关于我想从mysql的connection.query中取出结果并将其保存在nodejs的全局作用域链中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文