简体   繁体   English

提交的 Sequelize 事务的结果是“未定义”

[英]Result of committed Sequelize transaction is "undefined"

I am using a Sequelize transaction that returns successfully, however, the result is undefined.我正在使用成功返回的 Sequelize 事务,但是,结果未定义。 As stated in the documentation:如文档中所述:

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

Result should contain stuff!结果应该包含东西!

My code works and updates the database successfully, and enters the .then block, yet result logs as "undefined".我的代码工作并成功更新数据库,并进入.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
        })
    })
})

I really want the result of the user object, but no matter what I do, it remains undefined.我真的想要user对象的结果,但无论我做什么,它仍然是未定义的。 I have tried with and without returns on my subsequent functions within the transaction.我已经尝试过在交易中的后续函数有无回报。

Try this尝试这个

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

I was under the assumption that我的假设是

return createUser(body, {transaction: t})

would be "the result of the promise chain returned to the transaction callback将是“返回到事务回调的承诺链的结果

However, I needed to also return the user object in order to get it in result但是,我还需要返回用户对象才能获得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
                })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM