First I am searching the GroupMember model for all Groups the user is a member of. When they're found I get the result.
I want to loop through the result and get every group from the Group model. But how can I do an asynchronous function inside a for / forEach and go to the next iteration only when the asynchronous function is finished?
Because right now the groups array will get the first iteration over and over.
GroupMember.findAll({
Where : {
userID : userID
}
})
.then(function(result) {
var groups = []
var itemsProcessed = 0;
result.forEach(function(listItem, index, array) {
var groupID = listItem.dataValues.groupID;
Group.find({
Where : {
groupID: groupID
}
})
.then(function(group) {
groups.push(group.dataValues);
itemsProcessed++;
if(itemsProcessed === array.length) {
done(null, groups);
}
});
})
})
.catch(function(error) {
done(error);
});
EDIT
Group model
module.exports.getMyGroups = function(userID) {
return GroupMember.findAll({ attributes: ['groupID'], where: { userID: userID } })
.then(function(result) {
return Promise.all(result.map(function(listItem) {
var groupID = listItem.dataValues.groupID;
return Group.find({
attributes: ['groupName', 'groupDescriptionShort', 'createdAt'],
where: { id: groupID }
})
.then(function(group) {
return group.dataValues;
});
}));
});
}
Group controller calling the model
module.exports.myGroups = function(req, res) {
var userID = req.body.userID;
group.findByUserId(userID).then(
function(groups) {
respHandler.json(res, 200, { "groups": groups });
},
function(error) {
respHandler.json(res, 400, { "error": error });
});
}
Router calling the group controller
router.post('/groups', groupCtrl.myGroups);