node.js - 从等待返回的最佳实践
问题描述
这是我的注册路线:
hashed = await bcrypt.hash(req.body.password, bcryptRounds).catch(() => {
res.status(500).send();
return (null);
});
if (hashed === null) {
return;
}
result = await database.collection("profiles").insertOne({ "username": req.body.username, "password": hashed }).catch(() => {
res.status(500).send();
return (null);
});
if (result === null) {
return;
}
cookie = await SetAuthentification(result.ops[0]._id).catch((err) => {
res.status(500).send();
return (null);
});
if (cookie === null) {
return;
}
SetAuthentificationCookie(cookie, res);
res.status(200).send();
我需要在每次捕获后返回 (null) 并检查它以确保它没有失败,但这需要很多地方,而且与我之前的代码相比,我的代码变得不太清晰(但没有在错误情况)
hashed = await bcrypt.hash(req.body.password, bcryptRounds).catch(() => {
res.status(500).send();
});
result = await database.collection("profiles").insertOne({ "username": req.body.username, "password": hashed }).catch(() => {
res.status(500).send();
});
cookie = await SetAuthentification(result.ops[0]._id).catch((err) => {
res.status(500).send();
});
SetAuthentificationCookie(cookie, res);
res.status(200).send();
关于如何改进该部分以使其更清晰的任何想法?
解决方案
你为什么不把所有东西都包起来try...catch
?:
try {
const hashed = await bcrypt.hash(req.body.password, bcryptRounds);
const result = await database.collection("profiles").insertOne({
username: req.body.username,
password: hashed,
});
const cookie = await SetAuthentification(result.ops[0]._id);
SetAuthentificationCookie(cookie, res);
res.status(200).send();
} catch (err) {
res.status(500).send();
}
如果任何一个 Promise 被拒绝,代码执行就会跳转到catch
阻塞。
推荐阅读
- scala - 2个不同对象序列的Scala比较
- javascript - 无法从 API 获取数据并插入到 FlatList
- python - 如何在 Python 中使用 Regex 将凌乱的字符串拆分为字母和数字
- wordpress - 如何在函数 _content_template() 中获取图像的宽度和高度?
- python - 是否保证“多次”调用中的发布顺序?
- sql-server - Prometheus - 数据库访问
- bash - 用于汇总与名称关联的列的 Shell 脚本
- mysql - 更新整个 MySQL 数据库中的所有日期时间列值
- c - 在 if 条件内打印 char 的问题
- python - 等效于“kubectl wait --for”命令的 Kubernetes python 客户端