For my project, I am using electron and react with ipcRenderer and ipcMain to communicate with a database. I can see it go through the database, but it returns an empty array. It is like the array is returned before anything is read from the db.
Here is the code I am using in my ipc main: I am expecting it to return the names of the categories, but all it returns cateNames blank.
ipcMain.on(channels.GET_CATS, async(event,type) => {
console.log("made it")
let cateNames=[];
db.each(`SELECT name FROM categories WHERE type=?`, [type],(err, row) => {
if (err) {
return console.error(err.message);
}
console.log(row.name);
cateNames.push(row.name);
});
console.log(cateNames);
event.sender.send(channels.GET_LOGIN, cateNames);
});
I send the request with
ipcRenderer.send(channels.GET_CATS,"Donation");
with an ipcRenderer.on listening that will output the array to the console.
Javascript / Node.js execute commands in sequential order and does not "wait" when moving from one command to the next unless explicitely told to via the use of promises and async / await commands.
The reason your current code returns an empty cateNames array is becasue execution of the code does not "wait" for the db.each command to return it's callback. The callback is only returned once the DB has someting to return, which will either be a row or an error. This takes time. In the meantime, execution has moved on the next command.
To make this block of code "wait" until the DB has returned all available rows (if any) we could to use promises.
Instead, I propose a simpler method. Instead of pushing row.name with every db.each iteration, just use db.all and craft the response afterwards.
ipcMain.on(channels.GET_CATS, async(event, type) => {
console.log("made it")
let cateNames = [];
db.all(`SELECT name FROM categories WHERE type=?`, [type], (err, rows) => {
if (err) {
return console.error(err.message);
}
for (let row of rows) {
cateNames.push(row.name);
}
console.log(cateNames);
// Use event.reply(channel, data);
event.reply(channels.GET_LOGIN, cateNames);
});
});