sequelize中的Async getterMethods

时间:2017-08-25 16:05:57

标签: node.js postgresql sequelize.js

我试图找出如何在getterMethod中使用异步调用来工作。目标是我有一个模型wallet,钱包可以有很多walletTransactions。目标是在查询wallets时,它会发送名称为“余额”的虚拟字段。

我尝试了以下内容:

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

但没有任何运气。结果:

enter image description here

我做错了什么?

2 个答案:

答案 0 :(得分:2)

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

但是,根据您的使用情况,您可以绑定到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
          });        
      }
    }
  }  
});

答案 1 :(得分:0)

你能做的最好的事就是让你的吸气者回报承诺。问题是您可能希望属性balance是一个数字,但它实际上是对该数字的承诺。

你可以做你正在做的事情并说yourInstance.balance.then(theThingYouWant => { /* ... */ });

但是,这不是一个非常成熟的模式。