【发布时间】:2020-03-12 14:20:34
【问题描述】:
当我调用我自己使用 node.js 开发的 api,连接到 postgres (Sequelize) 数据库时,它返回以下 JSON:
[
{
"id": 1,
"name": "Wallet Name",
"wallet_type": "MN",
"icon": "fa fa-bank",
"color": "#000000",
"credit_limit": 3000,
"due_day": 22
}
]
我只需要,它在每个对象上再返回一行(account_value),即信息在另一个 javascript 函数中,所以它应该看起来像:
[
{
"id": 1,
"name": "Wallet Name",
"wallet_type": "MN",
"icon": "fa fa-bank",
"color": "#000000",
"credit_limit": 3000,
"account_value": 1200.55,
"due_day": 22
}
]
我当前的代码是:
async index(req, res) {
const wallets = await Wallet.findAll({
where: {},
attributes: [
'id',
'name',
'wallet_type',
'icon',
'color',
'credit_limit',
'due_day',
],
order: [['name', 'ASC']],
});
const finalObject = [];
wallets.forEach(async wallet => {
const currentItem = wallet.dataValues;
const { id } = await currentItem;
const { sum_credits } = await WalletsResume.sumCredits(id);
const { sum_debits } = await WalletsResume.sumDebits(id);
const sum_account_value = (sum_credits - sum_debits).toFixed(2);
currentItem.account_value = sum_account_value;
finalObject.push(currentItem);
console.log(`pushed ${id}`);
});
console.log(`-------------------------`);
console.log(finalObject);
return res.json(finalObject);
}
但是,当它返回一个空数组时:
[]
你能帮帮我吗?
我不知道如何修复它(我可以更改我所有的代码)
非常感谢!
【问题讨论】:
标签: javascript node.js asynchronous foreach sequelize.js