执行组合查询时出错
正在使用、 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})
}
}
不需要嵌套 promises 和 .then()
你可以只使用 await
因为 Sequelize
使用 promises。您的代码的主要问题是您在
.catch()
中使用了 try catch
并且它们都试图在失败时发送状态。所以很可能你的问题在其他地方,但这是一个副作用,当你运行我的代码时,你应该看到你的真正问题是否存在。
关于javascript - Node js中未处理的 promise 拒绝错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64509496/