我一直在使用async并等待一段时间,但这是我第一次使用sql。
首先,我通过创建路线做了一些简单的事情
const query = require('./src/helpers/sql')
app.get('/test', async (req, res) => {
const resultFromQuery = await query(`CatsWork_dashboard`)
console.log(`Result from Query:`, resultFromQuery)
res.send(resultFromQuery[0].id)
});
我的sql文件包含此(./src/helpers/sql')
// This file is responsible for performing all sql related operations
const mysql = require('mysql');
const config = require('./../config')
const pool = mysql.createPool({
host : config.DB_HOST,
user : config.DB_USER,
password : config.DB_PASSWORD,
database : config.DB_DATABASE
});
const getEverythingFromTable = async (tableName) => {
const queryResult = await pool.getConnection((error, connection) => {
if (error) throw error
const query = `SELECT * FROM ${tableName}`
console.log(`Query: `, query)
const queryResult = connection.query(query, (error, response) => {
console.log(`Response`, response)
if (error) throw error
connection.destroy()
return response
})
})
return queryResult
}
module.exports = getEverythingFromTable
现在,当我通过点击测试路径(从第一个代码片段开始)来测试查询时,日志
console.log(`Result from Query:`, resultFromQuery) // Result from Query: undefined
首先打印 get,然后从控制台显示getEverythingFromTable
中的所有日志。
我期望的是从resultFromQuery
中的查询中获取结果,然后执行console.log语句。
有人可以帮助我理解我做错了什么吗