到目前为止,这是我的上钩功能:
OrganisationSchema.pre('remove', function(next) {
Account.update({'organisations._id': this._id}, {$pull: {'organisations._id': this._id}}, {multi: true}, (err) => {
if (err) {
return next(err);
}
Invite.remove({organisation: this._id}, (err) => {
if (err) {
return next(err);
}
next();
});
});
});
这显然是行不通的,因为如果没有
Invite
文档,则将永远不会调用next
。最好我想要的是这样的:
OrganisationSchema.pre('remove', function(next) {
Account.update({'organisations._id': this._id}, {$pull: {'organisations._id': this._id}}, {multi: true}, next);
Invite.remove({organisation: this._id}, next);
});
但是此解决方案将触发
next
两次,可能导致应用程序崩溃。在调用
next
之前,是否有一种优雅的方式等待多个操作完成?我一直在考虑的一种解决方案是拥有一个完成操作的计数器,然后可以对照操作总数进行检查,但是我认为必须有更好的方法。 最佳答案
您的第一个示例应该起作用,因为即使没有Invite
文档,也总是调用回调函数。
但是,一种解决方案是使用诺言,因为猫鼬支持诺言:
OrganisationSchema.pre('remove', function(next) {
Promise.all([
Account.update({'organisations._id': this._id}, {$pull: {'organisations._id': this._id}}, {multi: true}).exec(),
Invite.remove({organisation: this._id}).exec()
])
.then(next)
.catch(next)
});