JavaScript wait for asynchronous function in if statement

pfMusk picture pfMusk · Jan 29, 2018 · Viewed 38.7k times · Source

I have a function inside an if statement

isLoggedin() has an async call.

router.get('/', function(req, res, next) {
    if(req.isLoggedin()){ <- never returns true
        console.log('Authenticated!');
    } else {
        console.log('Unauthenticated');
    }
});

how do i await for isLoggedin() in this if statement?

here is my isLoggedin function in which im using passport

app.use(function (req, res, next) {
   req.isLoggedin = () => {
        //passport-local
        if(req.isAuthenticated()) return true;

        //http-bearer
       passport.authenticate('bearer-login',(err, user) => {
           if (err) throw err;
           if (!user) return false;
           return true;

       })(req, res);
   };

   next();
});

Answer

Sterling Archer picture Sterling Archer · Jan 29, 2018

I do this exact thing using async/await in my games code here

Assuming req.isLoggedIn() returns a boolean, it's as simple as:

const isLoggedIn = await req.isLoggedIn();
if (isLoggedIn) {
    // do login stuff
}

Or shorthand it to:

if (await req.isLoggedIn()) {
    // do stuff
} 

Make sure you have that inside an async function though!