How do you bind queries using knex.js?

I'm having trouble understanding how promises works in Knex.js (uses Bluebird.js for promises). I am trying to make something rather simple, to execute different insert instructions in order, but I could not get it to work.

Here is the code that I still have that is designed to perform insertion in the authentication_type table, then insertion in user_table, and then insertion in the category table.

// Import database connection
var knex = require('./db-connection.js');

// Add a row to authentication_type table so that user 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?

+4
1

knex query , promises.

TL; DR: :

add_authentication_type()
  .then(add_default_user)
  .then(add_categories)

, , , :

// A
.then(add_default_user)
// B
.then(() => add_default_user())
// C
.then(add_default_user())
// D
.then(() => add_default_user)

then , . A add_default_user, . B , , . then , , promises.

C , , then, . promises, , , undefined, , , , .

D , , then, add_default_user!

, , ( " ", ).

foo()
  .then((fooResult) => bar(fooResult)
    .then((barResult)=> qux(barResult)
      .then((quxResult)=> baz(quxResult)
      )
    )
  )

, . , then, , then . , , , . , :

foo()
  .then((fooResult) => bar(fooResult))
  .then((barResult)=> qux(barResult))
  .then((quxResult)=> baz(quxResult))

** PROTIP: ** , Promise.resolve() :

Promise.resolve()
  .then(() => knex('table1').del())
  .then(() => knex('table2').del())
  .then(() => knex('table3').del())
+6

Source: https://habr.com/ru/post/1687056/


All Articles