0

So I've wrote a function to handle sqlite3 database run commands. From what I have read sqlite3 is async and I need to wrap queries in a promise. However, when I run this code (with new sqlite3.Database('UsersDb'), 'BEGIN TRANSACTION', []), I first get in console message "DEBUG: RunSql some code" and then 'DEBUG: OKKK'. I don't understand why, I feel like the order of messages should be reversed, that is the point of using promises...

I've been fighting with this for several hours now and I have no clue why this is not working.

// Takes database, sql command and parameters returns boolean informing about success
function sqlCmdRun(database, sql, parms) {
    let sqlCmd = new Promise((resolve, reject) => {
        database.run(sql, parms,  function (err) {
            if(err) {
                console.log(err.message);
                reject();
            }
            resolve();
        });
    });

    sqlCmd
        .then(function () {
            console.log("DEBUG: OKKK")
        }).catch(function () {
            console.log("DEBUG: ERROR EXECUTING sql:" + sql)
        });
    console.log("DEBUG: RunSql some code")
}
mikol
  • 185
  • 1
  • 10
  • 1
    Promises are asynchronous so the last `console.log` runs before the `then()` – charlietfl Aug 10 '19 at 12:34
  • Promises allow you to have an easy interface to queue up asynchronous callbacks, but they don't magically make asynchronous operations synchronous. You can use `await` to make the code *look* flatter, if you want - await the `sqlCommand` call, and then code under the `await` will run only once the Promise resolves – CertainPerformance Aug 10 '19 at 12:35
  • Think of it this way...if a promise took a minute to resolve, you wouldn't want everything else to stop working for that minute. Instead you want everything else to work and something to happen in the future when it does get resolved – charlietfl Aug 10 '19 at 12:39

0 Answers0