问题
I am a little new to promises and Sequelize. I am trying to insert a new user to my SQLite-database using constraint. In the User
-model I have flagged the email
-property as unique
, however when this constraint is not met the code inside the .then()
-block is still executed.
Code:
User.create({
email: uname,
password: psw
})
.then(console.log('success'))
.catch((err) => { console.log(err); });
Output:
Success
Executing (default): INSERT INTO `users` ...
{ SequelizeUniqueConstraintError: Validation Error ... }
No entry is of course added to the DB.
Expected output (when inserting unique value):
Executing (default): INSERT INTO `users` ...
success
Expected output (when inserting duplicate value):
Executing (default): INSERT INTO `users` ...
{ SequelizeUniqueConstraintError: Validation Error ... }
Any help would be very welcome, thank you!
回答1:
I see your mistake now:
User.create({
email: uname,
password: psw
})
.then(console.log('success'))
.catch((err) => { console.log(err); });
What you're doing here, is that instead of passing a function to the then(), you're executing a function. Of course it will run :D Change it to this:
User.create({
email: uname,
password: psw
})
.then(()=>{console.log('success')})
.catch((err) => { console.log(err); });
来源:https://stackoverflow.com/questions/60988694/promise-then-firing-on-sequelizeuniqueconstrainterror