【问题标题】:Result of committed Sequelize transaction is "undefined"提交的 Sequelize 事务的结果是“未定义”
【发布时间】:2023-03-30 22:44:01
【问题描述】:

我正在使用成功返回的 Sequelize 事务,但是结果未定义。如文档中所述:

.then(function (result) {
  // Transaction has been committed
  // result is whatever the result of the promise chain returned to the transaction callback

结果应该包含东西!

我的代码工作并成功更新数据库,并进入.then 块,但结果日志为“未定义”。

return sequelize.transaction(t => {
        return createUser(body, {transaction: t})
        .then(user => {
            if (user != null) {
                return createSetup({"user_id" : user.dataValues.id}, {transaction: t})
                .then(setup => {
                    console.log("setup was created")
                })
                .catch(err => {
                    throw new Error("the setup key was not created successfully... reverting transaction 2")
                })
            }
            else {
                throw new Error("no return value from creating user");
            }
        })
        .catch(err => {
            throw new Error("Failed to create user")
        })
    })
    .then(result => {
        console.log(result) //this returns undefined
        res.status(200).send({
            success: true,
            message: "The user was successfully created.",
        })
    })
    .catch(error => {
        console.log("error")
        res.status(400).send({
            success: false,
            message: error
        })
    })
})

我真的想要user 对象的结果,但无论我做什么,它仍然是未定义的。我已经尝试过交易中的后续函数有无返回。

【问题讨论】:

    标签: node.js sql-server transactions sequelize.js


    【解决方案1】:

    试试这个

    .then(setup => {
                        return { user, setup }
                    })
    

    【讨论】:

    • 尝试用 async/await 重构你的代码。真的很难读懂 then/catch 的所有嵌套块。
    【解决方案2】:

    我的假设是

    return createUser(body, {transaction: t})

    将是“承诺链返回给交易回调的结果

    但是,我还需要返回用户对象才能在result 中获取它

    return sequelize.transaction(t => {
            return createUser(body, {transaction: t})
            .then(user => {
                if (user != null) {
                    return createSetup({"user_id" : user.dataValues.id}, {transaction: t})
                    .then(setup => {
                        //this line is necessary to get the value in the result of the transaction
                        return user, setup
                    })
    

    【讨论】:

      猜你喜欢
      • 2020-07-04
      • 2011-03-13
      • 2015-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-03
      • 2011-04-30
      • 2016-02-12
      相关资源
      最近更新 更多