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?