Remember that once you introduce a return
statement, the function will immediately end. Subsequent iterations of the for
loop and the second loop will not execute. It is important to avoid returning in the middle of your loops.
If the order of transactions is not crucial, the most efficient method would be to utilize Promise.all
, which handles an array of promises and provides the results once all promises are fulfilled. With your existing logic, the implementation would resemble the following:
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) {
. . .
})
To further enhance your code, consider replacing the for loops with map
for a cleaner implementation:
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) {
// Conduct similar actions for user creation here
})
Alternatively, if maintaining order is crucial, you may need to implement a recursive function that processes each Promise sequentially.
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
})
}
Invoke the above function within your code:
return Room.create({ room_type: req.body.room_type }, { transaction: t })
.then(function (roomtype) {
return createRooms(t, req.body.roomtype)
})
.then(function (result) {
// Conduct similar actions for user creation here
})