代码之家  ›  专栏  ›  技术社区  ›  pfMusk

JavaScript在if语句中等待异步函数[重复]

  •  47
  • pfMusk  · 技术社区  · 7 年前

    if语句中有一个函数

    isLoggedin()具有异步调用。

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

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

    这是我的isLoggedin函数,其中im使用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();
    });
    
    2 回复  |  直到 5 年前
        1
  •  78
  •   Sterling Archer    7 年前

    我使用 async/await 在我的游戏代码中 here

    假设 req.isLoggedIn() 返回布尔值,简单如下:

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

    或速记为:

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

    确保你在 async 尽管功能强大!

        2
  •  11
  •   trincot Jakube    7 年前

    你可以 承诺 您的功能如下:

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

    然后你可以做:

    req.isLoggedin().then( isLoggedin => {
        if (isLoggedin) {
            console.log('user is logged in');
        }
    }).catch( err => {
        console.log('there was an error:', err); 
    });
    

    不要试图保持同步模式( if (req.isLoggeedin()) ),因为这将导致设计不良的代码。相反 完全异步编码模式:任何事情都有可能。