sequelize 中的异步 getterMethods

Tin*_*ino 1 postgresql node.js sequelize.js

我试图弄清楚如何在 getterMethod 中获得异步调用以工作。目标是我有一个模型wallet,钱包可以有很多walletTransactions。目标是在wallets查询时发送名称为“balance”的虚拟字段。

我尝试了以下方法:

getterMethods: {
      balance:  function() {
        return this.getWalletTransactions()
        .then((transactions) => {
          var balance = 0;
          transactions.forEach((value) => {
            balance = balance + value.amount;
          })
          return balance;
        })
      }
    } 
Run Code Online (Sandbox Code Playgroud)

但没有任何运气。结果:

在此处输入图片说明

我究竟做错了什么?

mcr*_*n18 5

getterMethod是同步的,因此您将无法运行承诺并在模型实例上返回已解析的值。

但是,根据您的用例,您可以绑定到afterFind钩子并运行异步操作:

const Wallet = db.define('wallet', {...}, {
  hooks: {
    afterFind: instances => {
      // instances is an array for the list view or an object for the detail view.
      if (Array.isArray(instances)) {
        performAsyncOperation()
          .then(data => {
            // loop over instances
          });        
      } else {
        performAsyncOperation()
          .then(data => {
            instances.dataValues.someNewProp = data.someField
          });        
      }
    }
  }  
});
Run Code Online (Sandbox Code Playgroud)