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(); });
async and await Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
By default, the execution of JavaScript code is asynchronous. It represents that JavaScript does not wait for a function to complete before starting on the other parts of the code.
Asynchronous requests will wait for a timer to finish or a request to respond while the rest of the code continues to execute.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With