我正在将Knex迁移与常规的promise方法一起使用,例如:
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'));
}
});
};
如何将其重构为使用异步/等待?整个结构(我们使用一堆promise方法返回knex.schema)使我陷入循环。
答案 0 :(得分:0)
类似的事情应该做:
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');
}