首页 > 解决方案 > Knex:为什么在没有下一次调用“then”的情况下调用“create table”不执行

问题描述

我面临下一个问题。如果我试图创建表,调用这些方法 - 没有结果:

    this.knexDB.schema
        .createTable("students", table => {
            table.increments("id");
            table.string("student_name");
            table.string("studnt_number");
        });

该表不创建。但是,如果我添加“then”的调用 - 表格会立即创建:

    this.knexDB.schema
        .createTable("students", table => {
            table.increments("id");
            table.string("student_name");
            table.string("studnt_number");
        })
        .then(() => {
            console.log("table created!");
        });

问题

  1. 为什么它会这样工作?
  2. 有什么方法可以create table使用更“合适”的方式立即调用?

标签: javascriptnode.jsdatabaseormknex.js

解决方案


Knex是一个查询构建器库,它具有可链接的 api,允许您链接不同的方法调用来构造查询。

事实上,db 查询实际上是一个异步操作,lib 作者决定在调用 api 之类的伪 promise 时“调用”db 查询。因此有必要调用then

如果你正在使用async&await你可以使用它,将隐式wait调用。then

await this.knexDB.schema.createTable('students', table => {
  table.increments('id');
  table.string('student_name');
  table.string('studnt_number');
});

推荐阅读