从非异步功能获得承诺

时间:2020-04-21 23:31:20

标签: javascript node.js express authentication

所以我的问题是,当我验证用户凭据时,login()的承诺还没有解决。因此,loginResult将为Promise {}。我知道我需要以某种方式等待结果,但是无论如何我还是可以想到的。

任何提示都值得赞赏。这是用于学校项目的,所以请不要对这有多不安全感指责我。

var express = require('express');
var router = express.Router();
var login = require('../controller/authenticate/login');

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

/* Login user */
router.post('/login', function (req, res, next) {
  const username = req.body.username;

  // This is a async return so its not working right. Currently only reading Promise{<pending>}
  let loginResult = login(username, req.body.password);

  console.log(loginResult)
  if (loginResult === true) {
    res.render('users', {username: username});
  }
  else {
    res.render('index', {error: true});
  }
});

module.exports = router;

1 个答案:

答案 0 :(得分:1)

喜欢吗?

在函数前添加async,然后await

router.post('/login', async function (req, res, next) {
  const username = req.body.username;

  const loginResult = await login(username, req.body.password);

  console.log(loginResult)

  if (loginResult === true) {
    res.render('users', {username: username});
  } else {
    res.render('index', {error: true});
  }
});

或使用Promises和then

router.post('/login', function (req, res, next) {
  const username = req.body.username;

  login(username, req.body.password)
    .then(resp => {
      console.log(resp)
      if (resp === true) {
        res.render('users', {username: username});
      } else {
        res.render('index', {error: true});
      }
    });
});