我正在使用 Knex 和 node.js 创建一个表并向其中插入一些数据。首先,我首先创建表,然后插入数据,但结果有时在插入数据时尚未创建表。然后我最终使用了如下回调。现在我混合了回调和 promise ,我不确定这是否是一件好事。我该怎么做才能在没有回调的情况下完成以下工作,并且仍然注意在插入数据之前创建表?
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);
最佳答案
一般来说,不鼓励混合回调和 Promise。我建议研究使用 Promises 的 async/await
模式,因为这通常更容易在代码中阅读。它也可以与 knex js 配合使用。
Node 回调的一个技巧是函数参数的约定,其中第一个参数是错误,第二个参数是成功结果。像这样: function (error, results) {...}
这使得结果很容易检查,就像
if(error) {
// do error stuff
return
}
// do success stuff with `results`
可以调用该函数,例如 next(new Error('bad'))
表示错误,或 next(null, 'success object')
表示成功.
您的回调next
仅采用一个参数,并且您没有检查其值。结果是“表存在”、“表已创建”还是“错误”对您下一步的操作很重要。
你可以尝试这样的事情:
async function handleInsert(tableName, res) {
try {
let hasTable = await knex.schema.hasTable(tableName)
if(!exists) {
let createResult = await knex.raw(`CREATE TABLE...`)
// check create results, throw if something went wrong
}
//table guaranteed to exist at this point
let insertResult = await knex(req.body.tableName).insert({
timestamp: req.body.timestamp,
deviceId: req.body.deviceId,
data: req.body.data,
})
debug(`Inserted with id: ${insertResult}`) //might need insertResult[0]
res.status(201).json({ success: true })
} catch(err) {
// any error thrown comes here
console.log('Server error: ' + err)
res.error('Bad thing happened, but do not tell client about your DB')
}
}
还有一件事。一般来说,您可以假设您需要的表已经存在。或者使用migration在服务器启动/更新时构建数据库。
关于mysql - Knex 创建数据库并向其中插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50876283/