javascript - 等待辅助函数响应
问题描述
好的,所以我的帐户实体有一个控制器,它具有以下辅助功能
// Verify user accessing is account owner
const verifyOwnership = (account_id, owner_id) => {
Account.findById(account_id, function (err, account) {
if (err) return next(err);
if (account.owner_id != owner_id) {
return false;
}
console.log("here");
return true;
});
};
而我的控制器的账户更新功能如下
exports.account_update = function (req, res, next) {
user_id = jwt.decode(req.headers["authorization"].slice(7)).id;
account_id = req.params.id;
// Verify user accessing is account owner
ownership_verified = verifyOwnership(req.params.id, user_id);
if (!ownership_verified) {
res.status(403).send({ error: "You are not allowed to access this account." });
return;
}
console.log(ownership_verified);
// Update account
Account.findByIdAndUpdate(account_id, { $set: req.body }, { new: true }, function (
err,
pet
) {
if (err) return next(err);
res.send({ message: "Account updated successfully.", account });
});
};
现在,我对这段代码有几个问题:
代码不等待verifyOwnership函数响应,ownership_verified的控制台日志未定义,那么“这里”就被记录了。使 verifyOwnership 函数异步/等待只是让它返回一个 Promise,因此一切都被处理为 true,我想改为等待 verifyOwnership 返回 true 或 false。
第二个问题更多是与猫鼬相关的逻辑问题,我希望如果 verifyOwnership 函数没有找到以使用提供的 ID 开头的帐户,则返回 404 表示未找到帐户,但也停止该函数就在那里调用它,不要继续更新,也不要发送“您不允许访问此帐户”消息。
抱歉发了这么长的帖子,并在此先感谢。
解决方案
推荐阅读
- javascript - 如果使用退格键输入另一个搜索或过滤条件,则响应表不会更新
- sockets - 自 Vista 发布以来,Microsoft 是否修复了 WSAPOLL?
- c# - 如何在 c# 中通过 LDAP SSL 从 Active Directory 的林中获取域
- r - 向量化滞后操作
- javascript - Passport JS localstrategy 允许使用电子邮件和用户名登录
- python - 如何在 Windows 上使用带有 mysql xampp 的“export-laravel-5-migrations _grt”插件
- javascript - Photoshop js脚本裁剪到选择,复制图层名称,并将图层名称粘贴到导出对话框中
- flutter - Flutter 升级 in_app_purchase 插件问题
- php - 根据子数组的值将第二级子数组移动到第一级多维数组的顶部
- javascript - 必填字段的错误放置问题