我在事务链代码中有多个循环,但在循环完成事务后立即提交链而不继续进行下一个查询。我的代码是这样的:
return sm.sequelize.transaction(function (t) {
return Room.create({
room_type: req.body.room_type
},{transaction: t}).then(function(roomtype){
for (i=0;i<room.length;i++){
return Roomtype.create({
name : req.body.roomtype[i]
},{transaction: t}); //my transaction only work untill here and commit after that
}
for (i=0;i<another.length;i++){ //I need to continue my query to second loop here
return User.create({
email :req.body.email[i]
},{transaction:t});
}
}).then(function(result){
}).catch (function(err){
})
})
那么如何让循环后的事务进入下一个循环呢?
最佳答案
请记住,一旦使用return
语句,函数就结束了。您的 for
循环将不再运行,第二个循环也不会运行。您需要在不在循环中间返回的情况下执行此操作。
只要交易顺序不重要,最好的方法就是使用 Promise.all
,它接受一个 promise 数组,并一次返回所有 promise 的结果他们都完成了。保留上面的其余逻辑,它看起来像这样:
return Room.create({
room_type: req.body.room_type
}, { transaction: t })
.then(function (roomtype) {
const promises = []
for (let i = 0; i < room.length; i++) {
const promise = Roomtype.create({
name : req.body.roomtype[i]
}, { transaction: t })
promises.push(promise)
}
for (let i = 0; i < another.length; i++){
const promise = User.create({
email :req.body.email[i]
}, { transaction: t })
promises.push(promise)
}
return Promise.all(promises)
})
.then(function (results) {
. . .
})
我会更进一步,将 for 循环替换为 map
。这不是绝对必要的,但会大大清理您的代码:
return Room.create({ room_type: req.body.room_type }, { transaction: t })
.then(function (roomtype) {
return Promise.all(req.body.roomtype.map(function (type) {
return Roomtype.create({ name: type }, { transaction: t })
}))
})
.then(function (roomResults) {
// Do the same thing for creating users here
})
或者,如果顺序很重要,您可能必须执行类似递归函数的操作,按顺序遍历每个 Promise。
const createRooms = function (transaction, types, index = 0) {
return Roomtype.create({ name: types[index] }, { transaction })
.then(function (result) {
if (index < types.length - 1) {
return createRooms(transaction, types, index + 1)
}
return result
})
}
然后您将在您的代码中调用该函数:
return Room.create({ room_type: req.body.room_type }, { transaction: t })
.then(function (roomtype) {
return createRooms(t, req.body.roomtype)
})
.then(function (result) {
// Do the same thing for creating Users here
})
关于javascript - sequelize 循环后继续事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48116474/