I have the following code snippet in an Electron app to retrieve a given column in a sqlite3 database:
database.js
var database = require("knex")({
client: "sqlite3",
connection: {
filename: path.join(__dirname, 'db/food.db')
},
useNullAsDefault: true
});
const fetchItems = (colName) => {
let itemList = database.select(colName).from('food')
itemList.then(() => {
// console.log(itemList);
return itemList;
}).catch((err) => {
console.log(err)
return [];
})
}
When I try accessing the array itemList
, I got a message undefined
. When I try printing it out to console, it shows lengthy info of the database object as following:
Builder [object] {
client: Client_SQLite3 {
config: { client: 'sqlite3', connection: [Object], useNullAsDefault: true },
logger: Logger {
_inspectionDepth: 5,
_enableColors: true,
_debug: undefined,
_warn: undefined,
_error: undefined,
_deprecate: undefined
},
connectionSettings: {
filename: '/home/.../db/food.db'
},
connectionConfigExpirationChecker: null,
driver: {
Database: [Function: Database],
Statement: [Function: Statement],
Backup: [Function: Backup],
OPEN_READONLY: 1,
...
How do I go about accessing the array (i.e. column) of values? Thanks.
Update: here is how I call this fetchItems
function in main.js
.
const database = require('./database');
ipcMain.on("showItemsButtonClicked", function () {
let itemList = database.fetchItems('food_name');
itemList.then(() => {
mainWindow.webContents.send("itemsRetrieved", itemList);
})
console.log(itemList);
});
I think you are using the wrong syntax.
const fetchItems = (colName) => {
let itemList = database.select(colName).from('food').then((res) => {
// console.log(res);
return res;
}).catch((err) => {
console.log(err)
return [];
})
return itemList
}
Using async await:
const fetchItems = async(colName) => {
try {
let itemList = await database.select(colName).from('food')
return itemList
} catch(err) {
console.log(err)
return [];
}
}