1

I have a function that queries SQL to get a string called Prefix.

function getPrefix(Guild) {
    let query = "SELECT Prefix FROM Guilds WHERE GuildId=?";
    Connection.query(query, [Guild.id], (err, result) => {
        if (err) throw err;
        return result[0].GuildPrefix;
    });
};

Whenever I print the Prefix out (console.log(result[0].Prefix);), it logs it fine - however, whenever I return it and then attempt to call the function, it always returns undefined.

I am using Node JS Version 10.15.1 & I am using MariaDB Version 10.1.37 on the Raspbian stretch of Debian. Please comment if I have left any other information out. Thanks.

William
  • 323
  • 4
  • 13

1 Answers1

0

In Nodejs the functions related to mysql are always asynchronous which means they will either not return anything or will retuen undefined.

So the solution is to use a callback function.
Eg.

function getPrefix(Guild, callback) {
    let query = "SELECT Prefix FROM Guilds WHERE GuildId=?";
    Connection.query(query, [Guild.id], (err, result) => {
        if (err){
         callback(JSON.stringify(err));
        };
        callback(JSON.stringify(result));
    });
};