我目前正在使用 knexjs 将数据插入到 sqlite 中,但我偶然发现了一个奇怪的问题。
此代码成功插入数据:
knex.insert({"request":requestquery,"date":date}).into("requests")
.then(function (id) {});
但是这段代码不会插入数据并且会默默地失败:
knex.insert({"request":requestquery,"date":date}).into("requests")
为什么then
代码很重要?为什么需要插入数据?
最佳答案
如果您没有调用 then()
,您仍然拥有查询构建器,并且仍然可以对其进行修改。
var q = knex("requests");
q.toString();
// 'select * from "requests"
q.where('id', 1).toString();
// 'select * from "requests" where "id" = 1'
q.orderBy('bar').toString();
// 'select * from "requests" where "id" = 1 order by "bar" asc'
// now query is actually executed and converted to promise
var promise = q.then(res => console.log('got', res));
因此,查询生成器是 Promise A+ 规范称为 thenable 的东西。它可用于逐段构建查询,并且直到用户想要触发它时才会触发正在构建的查询。
thenables 的一个优点是,如果你从 Promise 返回它们,它们的 .then()
函数将被调用并触发查询。
所以这无需调用内部查询即可工作:
knex('mydata').then(() => {
return knex('otherdata'); // no need to call .then here
}).then(otherDataResults => {
console.log(otherDataResults);
});
关于javascript - 使用 knexjs 将数据插入 sqlite 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42147363/