knex交易期待当时

时间:2018-04-25 21:42:27

标签: postgresql knex.js

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

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

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

1 个答案:

答案 0 :(得分:1)

您没有正确地在代码中返回promise,实际上您甚至没有调用rollback和commit函数。

这样的事情会更好:

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