2017-02-09 89 views
1

我目前使用knexjs將數據插入到sqlite中,但我偶然發現了一個奇怪的問題。用knexjs將數據插入sqlite時遇到困難

成功此代碼插入數據:

knex.insert({"request":requestquery,"date":date}).into("requests") 
      .then(function (id) {}); 

但是這個代碼不插入數據,並靜靜地失敗:

knex.insert({"request":requestquery,"date":date}).into("requests") 

爲什麼then代碼很重要?爲什麼需要插入數據?

回答

0

如果您不打電話給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 + spec調用可靠的東西。它可以用來逐個構建查詢,並且在用戶想要觸發它之前,正在構建的查詢不會被觸發。

有關可容錯的一件事是,如果你從promise中返回它們,它們的.then()函數將被調用並且查詢將被觸發。

所以這個工作,而無需調用再到內層查詢:

knex('mydata').then(() => { 
    return knex('otherdata'); // no need to call .then here 
}).then(otherDataResults => { 
    console.log(otherDataResults); 
});