简体   繁体   English

将 MySql 查询 output 存储在变量中(Node.js)

[英]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 个选择:

  1. You can place your entire follow up code inside the callback function:您可以将整个后续代码放在回调 function 中:
pool.query("select * from tblusers;", (err, res) => {
  const h = res
  // do whatever comes next here...
})
  1. Promisify the result of the callback function and await its resolution before moving on承诺回调 function 的结果并在继续之前等待其解决
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM