【问题标题】:knex transaction expecting a thenknex 交易期待一个 then
【发布时间】:2018-04-26 14:07:46
【问题描述】:

我遇到了一个问题,即 knex 事务需要一个 then。在下面的代码中,一旦发生回滚而不是捕获该错误,邮递员就会挂起等待响应。看起来它期待一个then。这是为什么?这意味着即使有回滚,事务也认为它是成功的?

app.post('/register', (req, res) => {
    const { email, name, password } = req.body;
    const hash = bcrypt.hashSync(password, saltRounds);
    console.log(hash);
    //insert syntax
    //When sending back response on an error from a server never send information back as error, instead send just a message
    dbConnection.transaction((trx) => {
        trx.insert({
            name: name,
            emailaddress: email,
            createddt: new Date()
        }).into('users')
        .returning('emailaddress')
        .then((response) => {
            console.log(response);
            dbConnection('login').insert({
            emailaddress: response,
            password: hash
            })
            .then(res.json('user created'));
        })
        .then(() => {
            trx.commit;
            console.log('committed');
        })
        .catch(() => {
            trx.rollback;
            //console.log(err);
            console.log('rollback');

            //res.json('cannot create user');
        })
        //.catch((err) => res.status(400).json(err))
    })
    //.then(res.json('user created'))
    .catch((err) => res.status(400).json('cannot create user'))
})

知道如何解决这个问题吗?

【问题讨论】:

    标签: postgresql knex.js


    【解决方案1】:

    您没有在代码中正确返回承诺,实际上您甚至没有调用回滚和提交函数。

    这样的做法会更好:

        dbConnection.transaction((trx) => {
            return trx.insert({
                name: name,
                emailaddress: email,
                createddt: new Date()
            }).into('users')
            .returning('emailaddress')
            .then((response) => {
                console.log(response);
                return dbConnection('login').insert({
                emailaddress: response,
                password: hash
                });
            })
        })
        .then((result) => res.json('user created'))
        .catch((err) => res.status(400).json('cannot create user'));
    

    【讨论】:

      猜你喜欢
      • 2014-05-22
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-11
      • 2021-03-04
      • 1970-01-01
      相关资源
      最近更新 更多