在电子中使用sqlite3,db.serialize剂量无法正常工作

时间:2017-10-17 02:23:53

标签: node.js sqlite electron

的package.json

{
  "main": "app/app.js",
  "scripts": {
    "postinstall": "install-app-deps",
    "start": "electron ."
  },
  "dependencies": {
    "sqlite3": "^3.1.8"
  },
  "devDependencies": {
    "electron-prebuilt-compile": "^1.7.9",
    "electron-builder": "^19.37.2",
    "electron-rebuild": "^1.6.0"
  }
}

的index.html

<body>
  <div id="app"></div>
  <div id='database'></div>
  <script>
    var sqlite3 = require('sqlite3').verbose();
    var db = new sqlite3.Database('./test.db')
    db.serialize(function () {
      var stmt = db.all("select * from BK_GROUP", function (_, rows) {
        console.log('end1');
      })
      var stmt2 = db.all("select * from BK_GROUP", function (_, rows) {
        console.log('end2');
      })
    })
    console.log('out1');
    db.close();
  </script>
  <script src="main.js"></script>
</body>

我希望(根据sqlite3&#39; api文档https://github.com/mapbox/node-sqlite3/wiki/Control-Flow)此代码应该像这样输出

end1
end2
out1

但实际输出是

out1
end1
end2 

我在网上遵循一些指示,安装电子重建并运行它

./node_modules/.bin/electron-rebuild

它也发现了sqlite3并重建它,但这没有用。

我还在package.json的脚本中添加了postinstall。

但是如果我在纯node.js env中运行此代码,它会输出正确的结果。

更多,如果我在电子中运行此代码,它会正确输出(首先打印结束,然后输出)。唯一的区别是这个代码在内存中打开数据库,上面打开一个文件数据库,位于硬盘驱动器上。

<body>
    <h1>electron-boilerplate-sqlite</h1>
    <ul id="database">
    </ul>
    <script>
      var sqlite3 = require('sqlite3').verbose();
      var db = new sqlite3.Database(':memory:');

      db.serialize(function() {
        db.run("CREATE TABLE lorem (info TEXT)");

        var stmt = db.prepare("INSERT INTO lorem VALUES (?)");
        for (var i = 0; i < 10000; i++) {
          stmt.run("Ipsum " + i);
        }

        stmt.finalize();

        var rows = document.getElementById("database");
        db.each("SELECT rowid AS id, info FROM lorem", function(err, row) {
          var item = document.createElement("li");
          item.textContent = "" + row.id + ": " + row.info;
          rows.appendChild(item);
        });
        console.log('end')
        setTimeout(() => console.log('delay'), 1000);

      });
      console.log('out')

      db.close();
    </script>
  </body>

我现在能做什么?

1 个答案:

答案 0 :(得分:0)

您误解了JavaScript,db序列化是回调函数,因此console.log的顺序是正确的,但是请记住一个

Since serialize() doesn't return until the last of its internal queries has completed, using it will hold off the close() until the query has completed.