[英]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 位数字“)他们在流程中使用的电话号码。
所以,我正在将 otp 更新到我的用户表,然后我需要添加调用以向用户发送 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})
}
}
没有必要嵌套承诺和.then()
你可以只使用await
因为Sequelize
使用承诺。
您的代码的主要问题是您在try catch
中使用.catch()
并且它们都试图在失败时发送状态。 因此,很可能您的问题出在其他地方,但这是副作用,当您运行我的代码时,您应该会看到真正的问题(如果存在)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.