JavaScript wait for asynchronous function in if statement
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!
You could promisify your function, like this:
req.isLoggedin = () => new Promise((resolve, reject) => {
//passport-local
if(req.isAuthenticated()) return resolve(true);
//http-bearer
passport.authenticate('bearer-login', (err, user) => {
if (err) return reject(err);
resolve(!!user);
})(req, res);
});
And then you can do:
req.isLoggedin().then( isLoggedin => {
if (isLoggedin) {
console.log('user is logged in');
}
}).catch( err => {
console.log('there was an error:', err);
});
Do not try to keep the synchronous pattern (if (req.isLoggeedin())
), as it will lead to poorly designed code. Instead, embrace fully the asynchronous coding patterns: anything is possible with it.