使用序列化交易时如何返回新创建的对象?

时间:2020-05-27 21:24:10

标签: javascript node.js sequelize.js

我有以下功能,当传递新的用户数据时,该功能有效。它将对象和子对象成功保存到mysql表中。但是考虑到我正在使用sequelize事务,一旦保存到数据库后,我该如何返回对象。

static async add(user) {
    let transaction; 
      try {
          // get transaction
        transaction = await models.sequelize.transaction();

        //  *****how to return the newly created user *****************************************

        models.User.create(user).then(newUser => {
          const id = newUser.id;

           //save address 
          if(user.address){

              address.userId = id;
              models.Address.create(address); 

          }
        }).catch(error => {
          throw error;
        }); 

        await transaction.commit();

      } catch (error) {
          console.log(error); 
            // Rollback transaction 
          if (transaction) await transaction.rollback();
          throw error;
      }
    }

1 个答案:

答案 0 :(得分:1)

尝试创建自动交易,使用await并在模型的transaction函数中指示create

static async add(user) {
      try {
        const createdUser = await models.sequelize.transaction(transaction => {
          const newUser = await models.User.create(user, { transaction })
           //save address 
          if(user.address){
            address.userId = newUser.id;
            await models.Address.create(address, { transaction }); 
          }
          return newUser;
        });
        // if you are here it means transaction already commited
        return createdUser;
      } catch (error) {
          // if you are here it means transaction already rolled back
          console.log(error); 
          throw error;
      }
    }