我试图找出如何在getterMethod中使用异步调用来工作。目标是我有一个模型wallet
,钱包可以有很多walletTransactions
。目标是在查询wallets
时,它会发送名称为“余额”的虚拟字段。
我尝试了以下内容:
getterMethods: {
balance: function() {
return this.getWalletTransactions()
.then((transactions) => {
var balance = 0;
transactions.forEach((value) => {
balance = balance + value.amount;
})
return balance;
})
}
}
但没有任何运气。结果:
我做错了什么?
答案 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 => { /* ... */ });
但是,这不是一个非常成熟的模式。