首页 > 解决方案 > 如何重构一段代码不使用异步函数

问题描述

我正在编写一个带有节点的代码,但同时我也在根据我在上一门课程中学到的知识以及其中的代码编写自己的应用程序。在代码中,我们有一个中间件,它检查以确保登录的用户是拥有配置文件的用户,然后允许他们修改它。这是使用异步函数编写的,它可以正常工作,但我想写为非异步函数,但我没有得到相同的最终结果,谁能帮我将这个函数重写为非异步函数?

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

标签: javascriptvalidationasynchronous

解决方案


该函数返回一个Promise对象(因此它是真实的)。如果你不使用async/await,你可以使用thenfunction 来完成 promise 并将剩下的代码放在回调中:

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

Promise请参阅和的文档then


推荐阅读