gpt4 book ai didi

callback - Sequelize - 在最后一次回调执行完成后从第二级链返回对象

转载 作者:行者123 更新时间:2023-12-03 22:39:33 42 4
gpt4 key购买 nike

在 addBussiness 方法中,我创建了一个业务对象,然后使用结果在数据库中使用 sequelize 创建一个 UserBusiness 对象。

我想返回在 UserBusiness 对象创建完成后创建的 Business 对象。

就目前而言,我认为由于 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
})
},

这是我在 Sequelize 中定义的映射:
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;
})
}

关于callback - Sequelize - 在最后一次回调执行完成后从第二级链返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51852316/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com