在Sequelize> = 1.7
we can use promises
var User = sequelize.define("user",{ username: Sequelize.STRING }) User .sync({ force: true }) .then(function() { return User.create({ username: 'John' }) }) .then(function(john) { return User.create({ username: 'Jane' }) }) .then(function(jane) { return User.create({ username: 'Pete' }) }) .then(function(pete) { console.log("we just created 3 users :)") console.log("this is pete:") console.log(pete.values) // what i want: console.log("this is jane:") console.log(jane.values) console.log("this is john:") console.log(john.values) })
UPD
所有值需要与其他模型的集合关联.
其实我需要一些像这样的代码:
User.hasMany(Group) Group.hasMany(User) User .sync({ force: true }) .then(function() { return User.create({ username: 'John' }) }) .then(function(john) { return User.create({ username: 'Jane' }) }) .then(function(jane) { return User.create({ username: 'Pete' }) }) .then(function(pete) { return Group.findOrCreate({id: 1}) }) .then(function(group) {return group.setUsers([john,jane,pete])}) .then(function(result) { console.log(result)}) })
解决方法
蓝鸟的方式是
collection helper functions.
如果要并行创建它们,请使用map
:
User.sync({ force: true }) .then(function() { return Promise.map( ['John','Jane','Pete'],function(name) { return User.create({ username: name }); }) }).spread(function(john,pete) { console.log("we just created 3 users :)") console.log("this is john:") console.log(john.values) console.log("this is jane:") console.log(jane.values) console.log("this is pete:") console.log(pete.values) })
如果您需要连续创建它们,请将其更改为mapSeries
(3.0).
如果数组不需要是动态的,而您只需要像在示例中一样通过承诺链传递共享值,请查看How do I access previous promise results in a .then() chain?.