0

I'm using node, javascript, vscode, sqlite3. I'm trying to grab the rowid after I insert a game record so I can use that as a foreign key to insert the details of the game. The record inserts, and this.lastID contains the rowid but no matter how I try my copy of rowid erases itself as soon as this.lastID goes out of scope.

//databaseinterface.js
function InsertNewGame() {
    let returnvalue;
    db.run("INSERT INTO Games DEFAULT VALUES", function(err) {
        if (err) {
          console.log(err.message);
        }
        // get the last insert id
        else {
          returnvalue = this.lastID;
console.log ("return value set at " + returnvalue);
        }
    });
    console.log("but at the end of insertnewgame return value is: " + returnvalue);
    return returnvalue;     

  };
module.exports.InsertNewGame = InsertNewGame;

//postheader.js
var express = require('express');
var bodyParser = require('body-parser');
const Database = require('../public/javascripts/databaseinterface');
var router = express.Router();
router.use(bodyParser.json()); 

router.post('/', function(req, res, next){
    
    let gameid = Database.InsertNewGame();  
    console.log("over in the router there is no sign of the returnvalue: " + gameid)
    res.send("Game " + gameid + " inserted");
});
module.exports = router;

In the console I get:

but at the end of insertnewgame return value is: undefined

over in the router there is no sign of the returnvalue: undefined

return value set at 16

why is returnvalue resetting? does it have anything to do with the console logs not being done in order?

mazoula
  • 1,221
  • 2
  • 11
  • 20
  • 1
    The function you pass to db.run executes after InsertNewGame has already returned. If you want to wait for it. You can use a promise. – John Dec 24 '20 at 08:10
  • any way to do that without summoning a bunch of additional libraries? an sqlite3 based solution? – mazoula Dec 24 '20 at 08:15
  • await db.run() could probably work if it returns a promise. Just gotta make your function async. Anyways, here you go https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise – John Dec 24 '20 at 08:16

0 Answers0