0

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.

  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ASDFGerte Aug 02 '20 at 02:26
  • @ASDFGerte That definitely is covering the right concept, but I'm having trouble figuring out how to apply it to my own code since the example is simpler and not in a node.js format. Callbacks and async/await have kinda confused me, but those are definitely what I need to make use of. Do you have any pointers on how to apply a callback to mine? – Syntthetix Aug 02 '20 at 02:55

0 Answers0