为什么带有 Bookshelf.js 的插入脚本会挂起?

Why does insert script with Bookshelf.js hang?

我有点困惑为什么 Node.js 脚本没有退出:

// myscript.js
var Model = bookshelf.Model.extend({
  tableName: 'models'
});
var m = Model.forge({name: 'hello'});
m.save();
console.log("End");

但是当 运行 使用 node myscript 时,脚本不会退出。

谢谢!

What is preventing the script from exiting?

Knex 拥有与您的数据库的连接池。虽然你的脚本执行结束了,但是Knex在后台还在维护这些,防止程序关闭。

How to cleanly exit after the model is saved?

您可以通过调用knex.destroy() 来断开所有数据库连接。您必须在查询完成后执行此操作。

// myscript.js
var Model = bookshelf.Model.extend({
  tableName: 'models'
});

Model.forge({name: 'hello'}).save().then(function(model) {

  console.log('model has been saved', model);

}).catch(function(error) {

  // it's bad practise to omit some sort of error reporting.
  console.error('something went wrong!');

}).finally(function() {

  // tear down connection.
  return bookshelf.knex.destroy();

}).then(function () {

  // This is the actual 'end' of the program.
  console.log("End");

});