[英]Store MySql query output in a variable (Node js)
I want to make an sql query and want to store the output in a variable.我想进行 sql 查询并希望将 output 存储在一个变量中。 I can't find any solution to make that work, can anyone help me please?我找不到任何解决方案来完成这项工作,有人可以帮助我吗?
const { createPool } = require("mysql")
const pool = createPool({
host:"localhost",
user:"root",
password:"",
database:"ticketsystem",
connectionLimit:10
})
const h = pool.query("select * from tblusers;", (err, res) => {
return res
})
console.log(h)
Your problem is related to the asynchronous nature of the JavaScript execution: the code located in the pool.query
's callback function runs after the assignation of the h
variable and after the console.log
.您的问题与 JavaScript 执行的异步性质有关:位于pool.query
的回调 function 中的代码在分配h
变量之后和console.log
之后运行。
You have 2 options:您有 2 个选择:
pool.query("select * from tblusers;", (err, res) => {
const h = res
// do whatever comes next here...
})
const h = await new Promise((resolve) => {
pool.query("select * from tblusers;", (err, res) => {
resolve(res)
})
})
console.log(h)
// do whatever comes next here...
Note that if you are not using one of the latest versions of node (supporting top level await), you will have to place everything in an IIFE function:请注意,如果您没有使用最新版本的节点之一(支持顶级等待),则必须将所有内容放在 IIFE function 中:
(async () => {
const pool = createPool({
host:"localhost",
user:"root",
password:"",
database:"ticketsystem",
connectionLimit:10
})
const h = await new Promise((resolve) => {
pool.query("select * from tblusers;", (err, res) => {
resolve(res)
})
})
console.log(h)
// do whatever comes next here...
})()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.