目前,我有点困惑于如何在返回查询结果之前正确地等待承诺完成
以下是我的当前代码:
const getLeaderboardValues = async () => {
const SQLConnection = await getSQLConnection();
return new Promise((resolve, reject) => {
SQLConnection.query(getValuesSQLQuery, (err, result) => {
if (err) { reject(err) }
return resolve(result);
});
SQLConnection.end()
})
}
const runtime = () => {
getLeaderboardValues().then((result) => {
console.log(result);
})
}上面的代码确实记录了正确的结果,但我相信这是因为我给了代码更多的时间来呈现断点,但是当正常运行时,我会得到未定义的
发布于 2022-05-22 16:59:45
我相信在返回查询之前,SQLConnection.end()行正在执行,因为它在query语句之外。
下面的内容可能解决了您的问题,但是我不建议在生产系统中打开一个连接并关闭它。
const getLeaderboardValues = async () => {
const SQLConnection = await getSQLConnection();
return new Promise((resolve, reject) => {
SQLConnection.query(getValuesSQLQuery, (err, result) => {
if (err) {
reject(err)
return SQLConnection.end()
}
SQLConnection.end()
return resolve(result);
});
})
}
const runtime = () => {
getLeaderboardValues().then((result) => {
console.log(result);
})
}https://stackoverflow.com/questions/72339561
复制相似问题