【发布时间】:2018-11-25 08:10:51
【问题描述】:
我正在使用带有 node.js 的 Knex 创建一个表并向其中插入一些数据。首先,我首先创建表,然后插入数据,但它最终导致有时在插入数据时尚未创建表。然后我最终使用了如下回调。现在我正在混合回调和承诺,我不确定这是否是一件好事。我该怎么做才能在没有回调的情况下进行后续工作,并且仍然注意在插入数据之前创建表?
function executeCallback(next, tableName) {
knex.schema.hasTable(tableName)
.then((exists) => {
if (!exists) {
debug('not exists');
// Table creation for mysql
knex.raw(`CREATE TABLE ${tableName} ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, timestamp BIGINT NOT NULL, deviceId VARCHAR(255) NOT NULL, data JSON )`)
.then((rows) => {
debug(rows);
next('Table created (mysql)');
})
.catch((err) => {
debug(`Error: ${err}`);
next(`Error: ${err}`);
});
} else {
debug('Table exists');
next('Table exists');
}
});
}
.
executeCallback((response) => {
debug('back from callback', response);
debug('insert');
knex(req.body.tableName).insert({
timestamp: req.body.timestamp,
deviceId: req.body.deviceId,
data: req.body.data,
})
.catch((err) => {
debug(`Error: ${err}`);
res.status(500).json({ success: false, message: `Error: ${err}` });
})
.then((dataid) => {
debug(`Inserted with id: ${dataid}`);
res.status(201).json({ success: true });
});
}, req.body.tableName);
【问题讨论】:
-
这能回答你的问题吗? Knex.js: Create table and insert data
标签: mysql node.js callback promise