the code like this:
(function () {
var tag = models.Tag.build({ create_time: new Date(), is_hot: '0', is_lock: '0', name: 'Nodejs' });
tag.save();
console.log(tag.dataValues);
tag.name = "npm";
tag.save();
console.log(tag.dataValues);
tag = models.Tag.build({ create_time: new Date(), is_hot: '0', is_lock: '0', name: 'webpack' });
tag.save();
console.log(tag.dataValues);
})();
the result is: the result
in my first eys,the result maybe:
Executing (default): INSERT INTO `t_tag` (`id`,`name`,`create_time`,`is_hot`,`is_lock`,`is_delete`) VALUES (NULL,'Nodejs','2016-12-23 03:09:23','0','0','0');
Executing (default): INSERT INTO `t_tag` (`id`,`name`,`create_time`,`is_hot`,`is_lock`,`is_delete`) VALUES (NULL,'npm','2016-12-23 03:09:23','0','0','0');
Executing (default): INSERT INTO `t_tag` (`id`,`name`,`create_time`,`is_hot`,`is_lock`,`is_delete`) VALUES (NULL,'webpack','2016-12-23 03:09:26','0','0','0');
what causes that ? why the "npm" record insert double time?
Sequelize functions run asynchronously. save
returns a promise, which you can .then()
off of to ensure that you're picking up after the SQL call has gone through. Since you're not doing that, the first save
hasn't persisted by the time you change tag.name
to "npm" and therefore "npm" is inserted twice (notice how all three console.log
calls execute before anything else happens -- this is another sign that you're not doing async properly). Fix your flow control to work with the promises and you won't have this problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With