我正在尝试将mySQL添加到password.js中,以对express.js中的用户进行身份验证,但似乎无法等待工作。Server.js:
initializePassport(
passport,
function(email) {
pool.getConnection(function(err, connection) {
if (err) throw err;
console.log("Connected!");
pool.query("SELECT * FROM users WHERE email = ?", email, function (err, result) {
if (err) throw err;
return result[0];
connection.release();
});
});
},
)
护照配置
function initialize(passport, getUserByEmail) {
const authenticateUser = async (email, password, done) => {
try {
const user = await getUserByEmail(email);
console.log(user)
} catch (e) {
return done(e)
}
现在,它只是为用户打印未定义的内容,然后打印已连接。我不确定为什么等待用户无法正常工作。
好吧,如果是getUserByEmail()
,那么它在异步操作完成时不会返回与之相关的promise,因此,执行await getUserByEmail()
不会等待任何事情。
await
仅在等待与要等待的操作相关的诺言时才有用。由于您甚至都没有在等待诺言,因此await
没什么用。您需要更改getUserByEmail()
,以便它返回一个已连接到您要等待的异步操作的Promise。
为了使函数返回连接到异步操作的Promise,您需要在该函数中的所有位置使用基于Promise的异步操作,而不是普通的回调异步操作。这些都是数据库操作,所有现代数据库现在都具有基于promise的接口,因此您真正想要做的就是将.getConnection()
,.query()
和.release()
切换为全部使用基于promise的操作。这也将使实现正确的错误处理以及与错误的调用者进行正确的通信变得更加容易。
我本人并不特别了解mysql,但这是一个一般性的想法。 Promise接口来自模块mysql2/promise
:
const mysql = require('mysql2/promise');
const pool = mysql.createPool({...});
initializePassport(passport, async function(email) {
let connection;
try {
connection = await pool.getConnection();
console.log("Connected!");
let result = await pool.query("SELECT * FROM users WHERE email = ?", email);
return result[0];
} catch(e) {
// log the error and the rethrow so the caller gets it
console.log(e);
throw e;
} finally {
if (connection) {
connection.release();
}
}
});