Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
162
rated 0 times [  164] [ 2]  / answers: 1 / hits: 23418  / 8 Years ago, mon, february 29, 2016, 12:00:00

I am currently building a Nodejs, Express, Sequelize (w. PostgreSQL) app, and have run into a few problems with using promises together with transactions and loops.



I am trying to figure out how to use a for loops in a transaction. I am trying to loop through a list of members and create a new user in the database for each of them.



I know the following code is wrong but it shows what I am trying to do.



Can anyone point me in the right direction?



        var members = req.body.members;
models.sequelize.transaction(function (t) {
for (var i = 0; i < members.length; i++) {
return models.User.create({'firstname':members[i], 'email':members[i], 'pending':true}, {transaction: t}).then(function(user) {
return user.addInvitations([group], {transaction: t}).then(function(){}).catch(function(err){return next(err);});
})
};
}).then(function (result) {
console.log(YAY);
}).catch(function (err) {
console.log(NO!!!);
return next(err);
});

More From » node.js

 Answers
4

You should use a Promise.all



    var members = req.body.members;
models.sequelize.transaction(function (t) {
var promises = []
for (var i = 0; i < members.length; i++) {
var newPromise = models.User.create({'firstname':members[i], 'email':members[i], 'pending':true}, {transaction: t});
promises.push(newPromise);
};
return Promise.all(promises).then(function(users) {
var userPromises = [];
for (var i = 0; i < users.length; i++) {
userPromises.push(users[i].addInvitations([group], {transaction: t});
}
return Promise.all(userPromises);
});
}).then(function (result) {
console.log(YAY);
}).catch(function (err) {
console.log(NO!!!);
return next(err);
});


I don't believe you need to catch within sequelize transactions as I think it jumps out to the catch on the transaction



Sorry for formatting. On mobile.



Promise.all will wait for all promises to return (or fail) before running the .then, and the .then callback will be all the promise data from each array


[#63109] Saturday, February 27, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chase

Total Points: 78
Total Questions: 106
Total Answers: 93

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
chase questions
Thu, Mar 31, 22, 00:00, 2 Years ago
Thu, Jul 1, 21, 00:00, 3 Years ago
Sat, Dec 12, 20, 00:00, 4 Years ago
Mon, Sep 14, 20, 00:00, 4 Years ago
;