I wrote a controller and I do not understand why in the method then my array is correct and I need to send it, and for .then () my array is empty. I can not send a res in the middle of the loop.
exports.getRecipientdata = (req, res) => {
const userId = req.params.recipientId;
const sendersArray = [];
Transaction.findAll({
where: {
id_recipient: userId,
},
}).then(transactions => {
for (let i = 0; i < transactions.length; i++) {
User.findOne({
where: {
id: transactions[i].id_sender,
},
attributes: ['id', 'name', 'surname'],
include: [
{
model: Transaction,
where: { id_sender: db.Sequelize.col('user.id') },
attributes: [
'amount_money',
'date_time',
'transfer_title',
'id_recipient',
'id_sender',
],
},
],
})
.then(sender => {
sendersArray.push(sender);
console.log(JSON.stringify(sendersArray)); // ok
})
.catch(err => {
console.log(err);
});
}
console.log('sendersArray', sendersArray); // empty?
res.send(sendersArray);
});
};