【发布时间】:2020-03-06 07:33:45
【问题描述】:
我正在尝试使用 npm 包 promise-mysql 并返回 json 数据(或字符串无关紧要),但我在使用 await/async 的 promise 链之后遇到了问题。
使用当前代码,我在 console.log 中收到 Promise { undefined },我在对用户的响应之前就有了。响应只是不向用户发送任何内容并将其关闭。任何人都可以指出如何调试它的正确方向吗?
index.js
app.get("/", async (req, res) => {
console.log( Promise.resolve(await getLogs()) )
res.send(await getLogs());
});
mysql.js
const mysql = require("promise-mysql");
let pool;
async function startDatabasePool() {
pool = await mysql.createPool({
connectionLimit: 10,
host: "xxx",
user: "xxx",
password: "xxx",
database: "xxx"
});
}
async function getDatabasePool() {
if (!pool) await startDatabasePool();
return pool;
}
module.exports = {
getDatabasePool,
startDatabasePool
};
users.js
const { getDatabasePool } = require("./mysql");
async function getLogs() {
let pool = await getDatabasePool();
pool.query("SELECT * from logs order by logdate desc", function(
error,
results,
fields
) {
if (error) throw error;
return JSON.stringify(results);
});
}
module.exports = {
getLogs
};
【问题讨论】: