我可以在 Sequelize 中将属性的 getter 定义为异步函数吗?
在 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 '';
}
}
},
...
记录我可以阅读正确的简历,例如:
昨天出生。喜欢阅读最好的 friend :Markus
但是我检索到的对象在bio属性中有一个空对象。
我想那是因为不支持异步功能,我错了吗?
如何在不使用异步函数的情况下实现这一点?
最佳答案
根据documentation getter 和 setter 不支持任何形式的异步。他们是同步的。因此无法使用异步函数(因为我们需要 promise 支持)。
这里还有一个 thread关于这个主题的讨论。并且已确认将来不会添加此功能。
您可以改为扩展模型并添加实例级方法。文档将其称为 virtual getter
。请看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 '';
}
}
关于javascript - Sequelize 中的异步 getter/setter 作为属性的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50641526/