我是Node JS的新手,我想用expressJS和Node.JS创建一个网站,我想创建一个异步查询函数,以便在变量中得到结果 - 这样我就可以使用这个函数了查询。
我使用以下代码创建db.js:
const mysql = require("mysql")
const connection = mysql.createPool({
host: "...",
user: "...",
password: "...",
database: "..."
})
var sql_statement = {...}
function queryResult(function(statement) { //Async function
connection.getConnection(function (error, connection) {
if (error) throw error
connection.query({...}), function (error, results)
connection.release()
return results
})
})
}
var output = queryResult(sql_statement)
console.log(output)
但它在示例作品中不起作用,它会在控制台中显示结果:
//code...
connection.getConnection(function (error, connection) {
if (error) throw error
connection.query({...}), function (error, results)
console.log(results)
connection.release()
})
})
//code...
信息:网站非常简单,我想使用此功能在网站上的expressJS中输出我的SQL数据,如下所示:
//code...
app.get("/", function (req, res) {
var sql_statement = {...} //SQL stmt for index.html
entries = queryResult(sql_statement)
res.render("index.html", {
title: "Home",
show_entires: entries
}
app.get("/articles", function (req, res) {
var sql_statement = {...} //SQL stmt for articles.html
entries = queryResult(sql_statement)
res.render("article.html", {
title: "Articles",
show_entires: entries
}
//code...