【发布时间】:2017-10-06 22:27:13
【问题描述】:
我在理解 Knex.js 中的 Promise 的工作原理时遇到了一些麻烦(使用 Bluebird.js 作为 Promise)。我正在尝试做一些非常简单的事情,依次执行不同的插入语句,但我无法让它工作。
这是我目前所拥有的代码,用于在 authentication_type 表上执行插入操作,然后在 user_table 上执行插入操作,然后在类别表上执行插入操作。
// Import database connection
var knex = require('./db-connection.js');
// Add a row to authentication_type table so that user's can be created
function add_authentication_type() {
return knex('authentication_type')
.insert({id: 1, name: 'Internal'})
}
// Add a 'default' user with nil uuid
// Anything added without a user must link back to this user
function add_default_user() {
return knex('user_table')
.insert({user_table_id: knex.raw('uuid_nil()'),
authentication_type: 1,
authentication_token: "default"})
}
// Add categories so that locations can be created
function add_categories() {
return knex('category')
.insert([
{name: "Hospital",
description: "Where people go to get healed"},
{name: "Police Dept",
description: "Where people go when there’s trouble"},
{name: "Fire Dept",
description: "Where all the fire trucks are"}])
}
// Run the functions in the necessary order to fit constraints
add_authentication_type()
.then(add_default_user()
.then(add_categories()))
我需要这些插入以正确的顺序从上到下发生,这样我就不会违反数据库的约束。这就是我试图通过在每个调用的 .then() 部分中链接调用来对最后几行进行的操作。我认为这会使第一个查询发生,然后是第二个,然后是第三个,但情况似乎并非如此,因为我在运行此代码时遇到约束违规错误。
我一直在阅读 Knex 和 Bluebird 的页面,但我无法掌握它。使用 Knex 执行这种顺序查询的正确方法是什么?
【问题讨论】:
标签: javascript node.js knex.js