2017-08-25 43 views
0

我想弄清楚如何在getterMethod中使異步調用工作。目標是我有一個模型wallet和錢包可以有很多walletTransactions。目標是當wallets被查詢時,它發送名稱爲'balance'的虛擬字段。Async getterMethods in sequelize

我曾嘗試以下:

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

,但沒有任何運氣。其結果是:

enter image description here

我在做什麼錯?

+0

你怎麼稱呼'getterMethods.balance'功能? – alexmac

+0

Wallet.find() - 沒什麼特別的 – Tino

+0

你如何使用這個調用的_result_?只要'let res = Wallet.find();的console.log(RES);'? – alexmac

回答

0

你可以在這裏做的最好的事情是讓你的getter返回承諾。問題在於你可能會預計財產balance是一個數字,但它實際上是該數字的承諾。

你可以做的正是你在做什麼,說yourInstance.balance.then(theThingYouWant => { /* ... */ });

但是,這並不是一個很既定模式。

0

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 
      });   
     } 
    } 
    } 
});