【问题标题】:Using Async/Await with Knex migrations将 Async/Await 与 Knex 迁移一起使用
【发布时间】:2018-12-05 10:24:25
【问题描述】:

我正在使用带有常规 promise 方法的 Knex 迁移,如下所示:

exports.up = function (knex) {
    return knex.schema
        .hasTable('table_name')
        .then(function (exists) {
            if (!exists) {
                return knex
                    .schema
                    .createTable('table_name', function (table) {
                        table.increments('id').primary();
                    })
                    .then(console.log('created table_nametable'));
            }
        });
};

我将如何重构它以使用 async/await?整体结构,我们返回 knex.schema 并带有一系列 promise 方法,这让我陷入了循环。

【问题讨论】:

    标签: async-await knex.js


    【解决方案1】:

    应该这样做:

    exports.up = async function (knex) {  
        if (! (await knex.schema.hasTable('table_name')) ) {
          await knex.schema.createTable('table_name', function (table) {
            table.increments('id').primary();
          });
        }
    
        // awaiting sequentially multiple promises to resolve one by one
        for (let item of arrayOfStuffToAwait) {
          await item;
        }
    }
    
    exports.down = async function (knex) {  
      await knex.schema.dropTable('table_name');
    }
    

    【讨论】:

      猜你喜欢
      • 2017-11-05
      • 2019-04-15
      • 2014-06-19
      • 2018-01-14
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多