node.js JavaScript 在 if 语句中等待异步函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48508020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:40:18  来源:igfitidea点击:

JavaScript wait for asynchronous function in if statement

node.jsexpressasynchronousecmascript-6passport.js

提问by pfMusk

I have a function inside an if statement

我在 if 语句中有一个函数

isLoggedin() has an async call.

isLoggedin() 有一个异步调用。

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?

我如何在这个 if 语句中等待 isLoggedin() ?

here is my isLoggedin function in which im using passport

这是我的 isLoggedin 功能,其中我使用的是护照

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();
});

回答by Sterling Archer

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

async/await这里用我的游戏代码做这件事

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

假设req.isLoggedIn()返回一个布尔值,它很简单:

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 asyncfunction though!

确保你在一个async函数中拥有它!

回答by trincot

You could promisifyyour 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, embracefully the asynchronous coding patterns: anything is possible with it.

不要试图保留同步模式 ( if (req.isLoggeedin())),因为它会导致代码设计不佳。相反,拥抱完全异步编码模式:一切皆有可能吧。