这是我的控制器当前的样子,它返回以下结果:
exports.getSenderdata = (req, res) => {
const userId = req.params.senderId;
Transaction.findAll({
where: {
id_sender: userId,
},
attributes: [
'amount_money',
'date_time',
'transfer_title',
'id_recipient',
'id_sender',
],
}).then(transactions => {
res.send(transactions);
});
};
//结果:
[
{
"amount_money": 5,
"date_time": "2019-01-19T20:15:07.000Z",
"transfer_title": "test",
"id_recipient": 2,
"id_sender": 1
},
{
"amount_money": 2,
"date_time": "2019-01-19T20:20:10.000Z",
"transfer_title": "payment example",
"id_recipient": 2,
"id_sender": 1
}
]
我想为json中的每个元素包含一个不同的表,该结果上的
id_recipient
=不同表中的id
。所以我想要这个结果>这可能吗?[
{
"amount_money": 5,
"date_time": "2019-01-19T20:15:07.000Z",
"transfer_title": "test",
"id_recipient": 2,
"id_sender": 1
"user": {
"name": "Claudie"
}
},
{
"amount_money": 2,
"date_time": "2019-01-19T20:20:10.000Z",
"transfer_title": "payment example",
"id_recipient": 2,
"id_sender": 1
"user": {
"name": "John"
}
}
]
我有一个需要的解决方案:我想发送此字符串,但不知道如何发送。
exports.getRecipientdata = (req, res) => {
const userId = req.params.recipientId;
const sendersArray = [];
Transaction.findAll({
where: {
id_sender: userId,
},
})
.then(transactions =>
Promise.all(
transactions.map(({ id_recipient }) =>
User.findAll({
where: {
id: id_recipient,
},
attributes: ['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 => {
console.log(JSON.stringify(sender)); // <- this is string, i need this to send res
})
.catch(err => {
console.log(err);
}),
),
),
)
.then(() => {
// ?
});
};
最佳答案
代替:
.then(sender => {
sendersArray.push(sender);
})
尝试:
.then(sender => {
sendersArray.push(sender);
if (sendersArray.length == transactions.length)
res.send(sendersArray);
})
并在最后删除
res.send(sendersArray);
。Promise.all
应该像这样工作:.then(transactions =>
Promise.all(
transactions.map(({ id_recipient }) => { return new Promise( (resolve, reject) => {
User.findAll({
where: {
id: id_recipient,
},
attributes: ['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 => {
resolve(JSON.stringify(sender)); // <- this is string, i need this to send res
})
.catch(err => {
reject(err);
}),
})}),
),
)
.then((results) => {
res.send(results);
});