首页 > 解决方案 > `UnhandledPromiseRejectionWarning: Unhandled Promise Rejection` 在我的节点应用程序中

问题描述

为了学习Node.js,我学习了一个他们使用 async/await 的课程,如下所示:

exports.signup = async (req, res) => {
  const userExists = await userExists.findOne({ email: req.body.email });
  if (userExists) {
    return res.status(403).json({
      error: "Email is taken!"
    });
  } else {
    const user = await new User(req.body);
    await user.save();
    return res.status(200).json({ user });
  }
};

但它让我UnhandledPromiseRejectionWarning崩溃了应用程序。

(node:10780) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise 
which was not handled with .catch(). (rejection id: 1)
(node:10780) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero 
exit code. 

似乎我没有处理错误部分,但我用我的 else 块做了它,它不是这样工作的吗?
任何帮助将不胜感激。

标签: node.js

解决方案


您需要await通过将其包围来从语句中捕获任何被拒绝的承诺try/catch

exports.signup = async (req, res) => {
   try {
      const userExists = await User.findOne({ email: req.body.email });
      if (userExists) {
        return res.status(403).json({
          error: "Email is taken!"
        });
      } else {
        const user = new User(req.body);
        await user.save();
        return res.status(200).json({ user });
      }
   } catch(e) {
       // some sort of internal error (probably database issue)
       console.log(e);
       res.sendStatus(500);
   }
};

这也删除了awaitin ,await new User(req.body)因为await只有当您await承诺并且new User()不是异步且不返回承诺时才会有用,因此没有理由使用await它。

请注意,为了避免两个单独的请求可能都发现用户不存在并且两个请求都可能尝试创建一个的竞争条件,您需要确保您的用户电子邮件在数据库中配置为唯一键,以便您永远不会为同一封电子邮件获得重复的用户。这是服务器编程中的一个微妙之处,理解它以避免竞争条件很重要。


推荐阅读