Search code examples
node-sqlite3

In node-sqlite3, how to wait until run() is finished?


With node-sqlite3 and the following code, INSERT can happen before CREATE TABLE finishes:

db.run("CREATE TABLE lorem (info TEXT)");
const stmt = db.prepare("INSERT INTO lorem VALUES (?)");
stmt.run("Ipsum");
stmt.finalize();

The documentation wraps the code in db.serialize(() => { ... }), but in my case this would make the code unwieldly. Is there any way to wait for db.run to finish? `


Solution

  • You can call db.serialize without an argument to serialize all following commands:

    db.serialize();
    db.run("CREATE TABLE lorem (info TEXT)");
    const stmt = db.prepare("INSERT INTO lorem VALUES (?)");
    stmt.run("Ipsum");
    stmt.finalize();