Express.js 使用护照等待

Express.js using await with passport

我正在尝试将 mySQL 添加到 passport.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)
    }

现在它只是为用户打印 undefined,然后打印 Connected。我不确定为什么 await 用户不工作。

好吧,如果那是 getUserByEmail(),那么它不会 return 连接到异步操作完成时的承诺,因此,执行 await getUserByEmail() 不会等待任何东西。

await 仅当您正在等待与您要等待的操作相关的承诺时才做一些有用的事情。由于您甚至没有等待承诺,因此 await 没有任何用处。您需要更改 getUserByEmail() 以便它 return 是一个连接到您试图等待的异步操作的承诺。

对于 return 连接到异步操作的 promise 的函数,您需要在该函数的任何地方使用基于 promise 的异步操作,而不是简单的回调异步操作。这些都是数据库操作,现在所有现代数据库都有一个基于承诺的接口,所以你真正想做的是将 .getConnection().query().release() 切换为所有使用基于承诺的操作.这也将使实施正确的错误处理和与错误调用者的正确通信变得更加简单。

我自己对 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();
        }
    }
});