节点 js 中未处理的承诺拒绝错误

Unhandled Promise Rejection Error in node js

执行组合查询时出错

正在使用,sequelize 和 mysql

这是我的代码:

const makeAuthenticate = async (req, res) => {
  const newOtp = Math.floor(100000 + Math.random() * 900000);
  try {
    const {phone} = req.body;
    
    const [user, created] = await db.User.findOrCreate({
      where: { phone: phone },
    })
      .then(e => {
         db.User.update({ otp: newOtp }, {
          where: {
            phone: phone
          }})
            .then(f => res.status(200).json({
              otp: newOtp
            }))
            .catch(err => res.status(500).json({error: err})) // Error comes from here !
      })
      .catch(err => res.status(500).json({error: err})) 
  } catch (error) {
    return res.status(500).json({error: error.message})
  }
}

下面是代码的作用:

基本上,我在单个查询中同时进行注册和登录,换句话说,首先使用 findOrCreate - 我找到用户或者我将创建一个新用户,然后我需要发送一次密码(这是临时的6 位数字”) 到他们在过程中使用的 phone 数字。

所以,我正在为我的用户更新 otp table,然后我需要添加调用以向用户发送 SMS(我还没有这样做)所以到目前为止我正处于findOrCreate 并再次调用特定用户的更新。

由此得到如下错误:

UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

尝试这样的事情

const makeAuthenticate = async (req, res) => {
  const newOtp = Math.floor(100000 + Math.random() * 900000)
  const {phone} = req.body
  
  try {
    const [user, created] = await db.User.findOrCreate({
      where: { phone: phone }
    })

    const updatedRes = await db.User.update({ otp: newOtp }, { where: { phone: phone }})

    res.status(200).json({
      otp: newOtp
    })
  } catch(e) {
    res.status(500).json({error: err})
  }
}

不需要嵌套 promise,.then() 你可以只使用 await 因为 Sequelize 使用 promise。

您的代码的主要问题是您在 try catch 中使用了 .catch(),并且它们都试图在失败时发送状态。因此,很可能您的问题出在其他地方,但这是一个副作用,当您 运行 我的代码时,您应该看到真正的问题(如果存在的话)。