首页 > 解决方案 > 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'});

标签: callbackpromisesequelize.jsgraphql-js

解决方案


您可以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;
  })
}

推荐阅读