I'm having some trouble understanding how the promises in Knex.js work (uses Bluebird.js for promises). I'm trying to do something pretty simple, execute different insert statements one after another in order, but I haven't been able to get it to work.
Here's the code I have so far, which is meant to execute an insert on the authentication_type table, then an insert on the user_table, and then an insert on the category 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()))
I need these inserts to happen in the correct order, from top to bottom, so I don't violate the constraints of my database. That's what I was attemping to do with the last few lines by chaining calls in the .then() portion of each call. I thought this would make the first query happen, then the second, then the third, but that doesn't appear to be the case since I get constraint violation errors when running this code.
I've been reading through the Knex and Bluebird pages, but I just can't get a grasp on it. What is the proper way to go about executing this kind of sequential querying with Knex?