我写了一个控制器,但我不明白为什么在该方法中为什么我的数组正确,所以我需要发送它,对于.then(),我的数组为空。我无法在循环的中间发送结果。
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);
});
};
答案 0 :(得分:1)
for
循环正在发出异步填充sendersArray
的请求。如果您在console.log(sendersArray)
循环运行之后for
同步地,则说明该循环尚未被填充。使用for
和.map
来等待所有请求完成,而不是Promise.all
循环:
exports.getRecipientdata = (req, res) => {
const userId = req.params.recipientId;
const sendersArray = [];
Transaction.findAll({
where: {
id_recipient: userId,
},
}).then(transactions => {
return Promise.all(transactions.map(({ id_sender }) => (
User.findOne({
where: {
id: 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);
})
.catch(err => {
console.log(err);
})
)));
})
.then(() => {
res.send(sendersArray);
});
};
另一种可能性是使用push
创建的数组,而不是Promise.all
来创建外部变量,并使用布尔值过滤以删除假值(因为catch
缺少返回值将导致undefined
数组的结果中出现Promise.all
个变量):
exports.getRecipientdata = (req, res) => {
const userId = req.params.recipientId;
Transaction.findAll({
where: {
id_recipient: userId,
},
}).then(transactions => {
return Promise.all(transactions.map(({ id_sender }) => (
User.findOne({
where: {
id: 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',
],
},
],
})
.catch(err => {
console.log(err);
})
)));
})
.then((sendersArray) => {
res.send(sendersArray.filter(Boolean));
});
};