如何修复异步 forEach 推送?

Leo*_*rdo 4 javascript foreach asynchronous node.js sequelize.js

当我调用我自己使用 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
  }
]
Run Code Online (Sandbox Code Playgroud)

我只需要,它在每个对象上再返回一行(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
  }
]
Run Code Online (Sandbox Code Playgroud)

我目前的代码是:

[
  {
    "id": 1,
    "name": "Wallet Name",
    "wallet_type": "MN",
    "icon": "fa fa-bank",
    "color": "#000000",
    "credit_limit": 3000,
    "due_day": 22
  }
]
Run Code Online (Sandbox Code Playgroud)

但是,当它返回一个空数组时:

[]
Run Code Online (Sandbox Code Playgroud)

你能帮我吗?

我不知道如何修复它(我可以更改我所有的代码)

非常感谢!

Abi*_*ido 5

Array.forEach 不等待异步调用。切换到for..in/for..of或常规 for 循环。

使用 for-of 的示例

async index() {
  // Fetch wallets here

  for (const wallet of wallets) {
    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}`);
  }

  // Then continue normally
}
Run Code Online (Sandbox Code Playgroud)

使用 for-in 的示例

async index() {
  // Fetch wallets here

  for (const walletIndex in wallets) {
    const currentItem = wallets[walletIndex].dataValues;
    // rest of code as above
  }

}
Run Code Online (Sandbox Code Playgroud)

  • 我的示例使用 for-of 而不是 for-in (2认同)