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

时间:2018-08-15 02:51:40

标签: callback promise sequelize.js graphql-js

在addBussiness方法中,我创建了一个业务对象,然后使用结果通过续集在数据库中创建一个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
      })
    },

以下是我的映射定义:

UserAccountModel.belongsToMany(BusinessModel, { through: UserBusinessModel, foreignKey: 'user_id'});
BusinessModel.belongsToMany(UserAccountModel, { through: UserBusinessModel , foreignKey: 'business_id'});

1 个答案:

答案 0 :(得分:0)

创建后可以返回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;
      })
    }

OR

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;
  })
}