如何重构一段代码以不使用异步功能

时间:2020-01-30 19:30:45

标签: javascript validation asynchronous

我正在编写带有节点跟随代码,但与此同时,我也根据我在上一门课程中学到的内容以及一个代码编写了自己的应用程序。 在其中的代码中,我们有一块中间件,可以进行检查以确保已登录的用户是拥有配置文件的用户,然后允许他们对其进行修改。这是使用异步函数编写的,并且按应有的方式工作,但是我想将其编写为非异步函数,但是我没有得到相同的最终结果,任何人都可以帮助我将此函数重写为非异步功能?

//Function to see if the current password is valid
middlewareObj.isValid = async (req, res, next) => {
  const { user } = await User.authenticate()(req.user.username, req.body.currentPassword);
  if(user) {
    //Add user to res.locals
    res.locals.user = user;
    next();
  } else {
    req.flash("error", "The password you entered does not match the current password stored in the database, please try again");
    res.redirect("back");
  }
}

我已经尝试过了,但是无论您在表单中的currentPassword字段中输入什么内容,它总是能给出真实的结果

//Function to see if the current email is valid
middlewareObj.isValid = (req, res, next) => {
  const user = User.authenticate()(req.user.username,
    req.body.currentPassword);
  if (user) {
    res.locals.user = user;
    next();
  } else {
    req.flash("error", "The password you entered does not match the current 
    password stored in the database, please try again");
    res.redirect("back");
  }
}

2 个答案:

答案 0 :(得分:1)

该函数返回一个Promise对象(这是事实)。如果您不使用async/await,则可以使用then函数来完成诺言,并将其余代码放在回调中:

//Function to see if the current password is valid
middlewareObj.isValid = function (req, res, next) => {
  (User.authenticate()(req.user.username, req.body.currentPassword)).then(({ user }) => {
    if (user) {
      //Add user to res.locals
      res.locals.user = user;
      next();
    } else {
      req.flash("error", "The password you entered does not match the current password stored in the database, please try again");
      res.redirect("back");
    }
  });
}

请参阅Promisethen的文档。

答案 1 :(得分:0)

这是最终有效的答案,

//Function to see if the current password is valid
middlewareObj.isValid = (req, res, next) => {
    const {user} = User.authenticate()(req.user.username, req.body.currentPassword).then(user => {
        if(!user.username && user.error) {
            req.flash("error", "The password you entered does not match the current password stored in the database, please try again");
            res.redirect("back");
        } else {
            res.locals.user = user;
            next();     
        }   
    });
}

还要感谢Mickael B的帮助