I'm using MySQL in a discord.js bot as a way to learn how to implement SQL in an actual program. In the process, I found that I can't seem to return a value from within the two nested functions used for the database connection/query, so the value I need to return always comes back as undefined.
Here's the code:
let getChannel = (chanType) => {
var chanID; // Value that needs to be updated and then returned
db.getConnection((err, con) => {
con.query(`SELECT * FROM channels WHERE type = '${chanType}'`, (err, rows) => {
if (err) throw err;
chanID = rows[0].id; // Update the chanID variable with the needed channel ID
// Still holds value here
con.release();
});
});
return chanID; // Code seems to lose chanID's value right here, or upon leaving the con.query arrow function
}
Basically, I call getChannel() from another file, expecting it to return the ID of the channel requested (in this case, the ID of the channel with the 'quotes' type assigned to it in the database). Instead, chanID gets reverted to 'undefined', so the whole system breaks once I try to return that value.
I've tried a million different configurations of this to try and make the getChannel()
function return chanID
, and it just won't work. Any help would be extremely appreciated.