节点Knex插入未执行

时间:2016-06-30 06:56:43

标签: node.js knex.js

我正在节点中执行这个膝关节查询:

return Knex.transaction(function (tx) {
        debug("Inserting new story record");
        return tx.insert({
            'projectId':projectId,
            'title': title,
            'story': text,
            'points': 0,
            'storyNumber': Knex('story').max('storyNumber').where('projectId', projectId)
        }, 'id')
            .into('story')
            .then(function (id) {
                debug("Returning story for %s", id);
                return getStory(id);
            })
    })

但是'then()'函数永远不会被调用。谁知道为什么?

我一直在阅读所有knex doco,看来我已经做好了一切。命令的调试如下所示:

crux:db Inserting new story record +4ms
{ method: 'insert',
  options: {},
  timeout: false,
  cancelOnTimeout: false,
  bindings: [ 0, 2, 'test', 2, 'title' ],
  __knexQueryUid: 'aa5ff1d3-eff0-4687-864b-772c26e1aebd',
  sql: 'insert into `story` (`points`, `projectId`, `story`, `storyNumber`, `title`) values (?, ?, ?, (select max(`storyNumber`) from `story` where `projectId` = ?), ?)' }

所以这对我来说都很好看。永远不要执行。

1 个答案:

答案 0 :(得分:0)

需要更多信息......您可能永远不会触发交易。在调用.then或尝试在promise链中解析之前,不会执行事务(QueryBuilder和Transaction是Promise A + spec调用thenables https://promisesaplus.com 1.2)。

其他可能性是insert会抛出错误并且所有内容都会回滚,然后才会被调用。

尝试这个处理一些错误案例并可能帮助您找出真正原因的那个:

return Knex.transaction(function (tx) {
  debug("Inserting new story record");
  return tx.insert({
    'projectId':projectId,
    'title': title,
    'story': text,
    'points': 0,
    'storyNumber': Knex('story').max('storyNumber').where('projectId', projectId)
  })
  .into('story')
  .then(function (id) {
    debug("Returning story for %s", id);
    return getStory(id);
  })
  .catch(function (err) {
    debug("Insert failed", err);
    throw err;
  })
})
// just to make sure that transaction is triggered (in your code caller is responsible of that)
.then(function (blah) { return blah; }); 
.catch(function (err) { debug("Huh! Transaction failed!", err); throw err; });

同样在.insert({...},返回)中你似乎使用了不支持传递返回参数的mysql。所以我从我的建议中删除了它......

相关问题