'Should I pass async function to passport.deserializeUser()?

I am using passport to handle user authentication. During initialization, I have to do the following for managing the session cookies:

passport.serializeUser((user, done) => done(null, user.ID));
passport.deserializeUser((id, done) => done(null, getUserById(id)));

Here, I have stored the users in my database, so getUserById is an asynchronous function, defined as follows:

const getUserById = async (id) => {
    result = await executeQuery(`SELECT ID, USERNAME, PASSWORD FROM STUDENTS WHERE ID=:id`, [id]);
    if (result.rows.length != 0) return result.rows[0];
    else return null;
};

Here, getUserById(id) function does not immediately return the result from query execution, it returns a promise. What is the proper way to pass this getUserById() function to done()?

  • Should I wrap getUserById(id) in another IIFE async function?
  • Or should I do the following?
passport.deserializeUser(async (id, done) => {
    const user = await getUserById(id);
    done(null, user);
});


Solution 1:[1]

The first solution that comes to mind:

passport.deserializeUser((id, done) => {
    getUserById(id).then(user => done(null, user))
};

I.e., handle the promise using then(). I don't know if deserializeUser will take an asynchronous call-back function. I do know some functions like useEffect in React don't.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeremy Caney