Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript wait for asynchronous function in if statement [duplicate]

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(); }); 
like image 756
pfMusk Avatar asked Jan 29 '18 18:01

pfMusk


People also ask

How do you wait for asynchronous function?

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.

Does JavaScript wait for async function to finish?

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.

Does async wait for response?

Asynchronous requests will wait for a timer to finish or a request to respond while the rest of the code continues to execute.


1 Answers

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!

like image 118
Sterling Archer Avatar answered Sep 24 '22 01:09

Sterling Archer