callback - Sequelize - 在最后一次回调执行完成后从第二级链返回对象
问题描述
在 addBussiness 方法中,我创建了一个业务对象,然后使用结果在数据库中使用 sequelize 创建一个 UserBusiness 对象。
我想返回在 UserBusiness 对象完成创建后创建的业务对象。
就目前而言,我认为由于 Javascript 的异步特性,在 UserBusiness 对象完成创建之前返回了业务对象。
有没有办法从第二个回调中的第一个回调返回对象?
addBusiness(_,args) {
// this is needed to put it correctly in the geometry point format that the database expects
var point = { type: 'Point', coordinates: [args.input.location.longitude,args.input.location.latitude] };
args.input.location = point;
return Business.create(args.input, {
include: [{
association: Hours,
as: 'hours'
}]
}).then(business => {
UserBusiness.create({userId: args.input.userId, businessId: business.businessId})
return business; // this might get returned before UserBusiness.create is done executing
})
},
这是我在续集中定义的映射:
UserAccountModel.belongsToMany(BusinessModel, { through: UserBusinessModel, foreignKey: 'user_id'});
BusinessModel.belongsToMany(UserAccountModel, { through: UserBusinessModel , foreignKey: 'business_id'});
解决方案
您可以UserBusiness
在创建后返回对象,然后UserBusiness.bussiness
将业务对象返回或保存在一个变量中,并在创建对象后返回该变量UserBusiness
。
addBusiness(_,args) {
var point = { type: 'Point', coordinates: [args.input.location.longitude,args.input.location.latitude] };
args.input.location = point;
return Business.create(args.input, {
include: [{
association: Hours,
as: 'hours'
}]
}).then(business => {
return UserBusiness.create({userId: args.input.userId, businessId: business.businessId})
}).then(UserBusiness => {
return UserBusiness.business;
})
}
或者
addBusiness(_,args) {
var _business;
var point = { type: 'Point', coordinates: [args.input.location.longitude,args.input.location.latitude] };
args.input.location = point;
return Business.create(args.input, {
include: [{
association: Hours,
as: 'hours'
}]
}).then(business => {
_business = business;
return UserBusiness.create({userId: args.input.userId, businessId: business.businessId})
})
.then(() => {
return _business;
})
}
推荐阅读
- c# - 从文本文件读取时值被覆盖
- python - 如何克服这个“'模块'对象不可调用”
- android - ContentResolver.openAssetFileDescriptor 抛出 java.io.FileNotFoundException: No entry for content://media/external/audio/media
- spring - 如何在spring boot中声明多个具有相同类但使用不同属性的对象
- java - 如何获取在 Android 的列表视图中单击的项目的字符串值
- xslt - 删除 XSLT 中两个字符串和节点之间的空格
- python - 如何获取每个标签值对应每个`user_id`的比例
- sql - Oracle SQL 我无法分组
- python - 如何将第 i 行的 numpy 数组的单个元素与第 i 行的另一个 numpy 数组的元素相乘?
- http - 如何处理python请求中的“无法建立新连接”错误