我可以在Sequelize中将属性的getter定义为asyc函数吗?
在getter中我应该从另一个表中检索一个值,我在模型定义中尝试了这个:
...
bio: {
type: Sequelize.STRING,
get: async function() {
let bio = this.getDataValue('bio');
if (bio) {
let bestFriend = await db.models.User.findById(this.getDataValue('BestFriendId'))
if(bestFriend){
bio += ` Best friend: ${bestFriend.name}.`;
}
console.log(bio)
return bio;
} else {
return '';
}
}
},
...
记录我可以通过以下方式读取正确的bio:
昨天出生.喜欢读最好的朋友:马库斯
但是我检索的对象在bio属性中有一个空对象.
我想这是因为不支持异步功能,我错了吗?
如何在不使用异步功能的情况下实现此目的?
解决方法:
根据documentation getter和setter不支持任何形式的异步.它们是同步的.所以没有办法使用异步函数(因为我们需要一个promise支持).
这里还有一个关于这个主题的讨论.并且已经确认将来不会添加此功能.
您可以改为扩展模型并添加实例级方法.该doc称它为虚拟吸气剂.请参阅this article.
您还可以使其异步并访问模型数据.
BioModel.prototype.getBio = async function() {
let bio = this.getDataValue('bio');
if (bio) {
let bestFriend = await db.models.User.findById(this.getDataValue('BestFriendId'))
if(bestFriend){
bio += ` Best friend: ${bestFriend.name}.`;
}
return bio;
} else {
return '';
}
}