首页 > 解决方案 > 从等待返回的最佳实践

问题描述

这是我的注册路线:

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();

关于如何改进该部分以使其更清晰的任何想法?

标签: node.jsasync-await

解决方案


你为什么不把所有东西都包起来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阻塞。


推荐阅读