0

I am using the sqlite3 module for node.js with the Electron Module. I am new to javascript and am struggling with callbacks and asynchronous code.

My intent is for the getTable function to run, build the table array and pass that array through to the callback function which is the useTable function.

So this function should build and pass the table array:

function getTable(callback) {
    const sqlite3 = require('sqlite3').verbose();
    var testDatabase = new sqlite3.Database('app/data/testDatabase.db');
    var table = [];
    var testRow = [];
    testDatabase.each("SELECT * FROM test_Accounts", function(err, row) {
        testRow.push(row.test_id);
        testRow.push(row.test_creation_date);
        testRow.push(row.domain);
        testRow.push(row.test_login_url);
        table.push(testRow);
        testRow = [];
    });
    testDatabase.close();
    callback(table);
}

And this function will take the table array and use it:

function useTable(table) {
    //code that uses the table array passed to this function from the getTable function.
}

And I would run this like this:

getTable(useTable);

When I run this, the console shows no errors. It seems the the useTable function runs before the table array is completed in the getTable function which I thought was one of the main purposes of a callback, to wait for asynchronous code to run (in this case building an array) before taking that array and passing it through to another function.

How do I make sure that the table array in the getTable function is completely generated before passing it through and running the useTable function?

Bogarto
  • 37
  • 5

1 Answers1

1

You should use testDatabase.all function to get all your rows at once. For example:

testDatabase.all('SELECT * from test_accounts',callback)

Please see the documentation:

Runs the SQL query with the specified parameters and calls the callback with all result rows afterwards. https://github.com/mapbox/node-sqlite3/wiki/API#databaseallsql-param--callback

One more note: In NodeJS, when you call to callback functions it's recommended to use the first returned value as null or the error value.

function useTable(err,table){
  if (err){
     throw Err
  }
  else {
     // Do something with the data
  }
}

getTable(useTable)
Aminadav Glickshtein
  • 23,232
  • 12
  • 77
  • 117