javascript - 如何重构一段代码不使用异步函数
问题描述
我正在编写一个带有节点的代码,但同时我也在根据我在上一门课程中学到的知识以及其中的代码编写自己的应用程序。在代码中,我们有一个中间件,它检查以确保登录的用户是拥有配置文件的用户,然后允许他们修改它。这是使用异步函数编写的,它可以正常工作,但我想写为非异步函数,但我没有得到相同的最终结果,谁能帮我将这个函数重写为非异步函数?
//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");
}
}
解决方案
该函数返回一个Promise
对象(因此它是真实的)。如果你不使用async/await
,你可以使用then
function 来完成 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");
}
});
}
推荐阅读
- angularjs - AngularJS:在初始化时获取指令中的插值属性值
- angular - 如何使用 ng2 智能表(ServerDataSource)在标头中传递身份验证令牌
- html - 将输入字段与长输入名称对齐
- php - 使用 PHP + MySQLi 的 UPDATE 查询有效,但始终在数量字段上设置 0
- javascript - 单击 div 时在 EJS 中显示 JSON 对象
- c++ - c ++ Vector fetch方法在Release中返回nullptr但不是Debug
- v8 - 在 JSON 解析后获取解析值(嵌入式 v8)
- bash - 使用远程数据完成 Cobra 标志 bash
- c++ - 退出 PCL 查看器:即使窗口关闭,wasStopped() 也不会改变值
- django - 我正在尝试在 AWS 上发布销售商商店并使用 Apache