Knex.js:如何创建表,插入数据,获取选择的查询结果然后返回

时间:2018-07-15 00:36:24

标签: javascript promise knex.js

以下代码段创建了数据库文件,创建了表,插入了数据,查询并输出了数据,但随后却挂起了。

我需要它返回查询结果,输出到控制台,然后结束该过程。

我想念什么?

const knex = require('knex')({
    client: 'sqlite3',
    // debug: true,
    connection: {
    filename: "example.db"
    },
    useNullAsDefault: true
});

const data = [
    {
        col1: "one",
        col2: "two",
        col3: "three"
    },
    {
        col1: "a",
        col2: "b",
        col3: "c"
    },
    {
        col1: "1",
        col2: "2",
        col3: "3"
    }        
];

knex.schema.createTable('myTable', table => {
    table.increments();
    table.string("col1");
    table.string("col2");
    table.string("col3");
})
.then(function(){
    return knex('myTable').insert(data);
})
.then(function(){
    return knex('myTable').select();
})
.then(console.log);

1 个答案:

答案 0 :(得分:0)

添加knex.destroy()调用似乎有所帮助;它确实解决了诺言,但是我不确定这是否正确。

knex.schema.createTable('myTable', table => {
    table.increments();
    table.string("col1");
    table.string("col2");
    table.string("col3");
})
.then(function(){
    return knex('myTable').insert(data);
})
.then(function(){
    return knex('myTable').select();
})
.finally(function(queryResult){
    knex.destroy();
    return queryResult;
})
.catch(console.error);