问题
am getting error while executing combined queries
Am using, sequelize and mysql
Here is my code:
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})
}
}
And here is what am doing with the code:
Basically, am doing both signup and signin in single query, in other words at first using findOrCreate - i find the user or i will create a new user, and then i need to send one time password (which is temp 6 digit numerics") to the phone number which they use on the process.
So, am updating the otp to my users table and then i need to add up the call to send SMS to the user ( i havent done that yet ) so as of now am at the stage of findOrCreate and make another update call to the specific user.
By this am getting an error as follows:
UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
回答1:
Try something like this
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})
}
}
There is no need to nest promises and .then()
you can just use await
since Sequelize
uses promises.
The main issue with your code is that you use .catch()
inside try catch
and they both are trying to send a status on failure. So most likely your issue is somewhere else but this was a side effect, when you run my code you should see your real issue if it exist.
来源:https://stackoverflow.com/questions/64509496/unhandled-promise-rejection-error-in-node-js