Promise.then() firing on SequelizeUniqueConstraintError

别等时光非礼了梦想. 提交于 2020-04-17 22:18:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!