0

Iv been scratching my head over this for quite a while now, and a massive search over the internet has proved unsuccessful. Hopefully somebody here can help.

Im trying to set the value of a variable by calling a function, but the function contains a Promise. and is only returning and empty string value.

Here is my code (I will walk through it):

//make connection to mysql DB
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '*********',
database: 'prioritySpeaker'
});
var table = 'speaker';
connection.connect(function(err, results) {
    if (err) {
        console.log("ERROR: " + err.message);
        throw err;
    };
    console.log("connected.");
});
    var priorityRole = role();
    function role(){
        var role = "";
        connection.query(`SELECT priorityRole from ${table} WHERE uniqueID = "${guildID}"`,function(error,result,field){
        if(result){
            var row = result[0];
            var pRole = row.priorityRole;
            role = pRole;
        }else{
            console.log(error);
        }
    });
    return role;
};
console.log(priorityRole);

So what is happening is: I've created a variable called priorityRole which needs to be the resulting value from the resultof the connection.query.

The function role() creates a variable of role and then runs the connection.query to the mysql server which if it returns with a result should set the value of role to the result as defined in the if statement and then return role as the result. So at the very end I need the priorityRole variable to be the same as the role variable.

Hopefully that all makes sense. I should mention that I am using NodeJS, and I really hope that somebody will be able to help me out with this :)

Ashton
  • 41
  • 3
  • 1
    FYI, I don't know why you think there's a promise in this code. I don't see one. What there is in there is an asynchronous operation which means you cannot directly return the value from the function because the function will return BEFORE the value has even been retrieved. So, you have to either pass in a callback which you will call when the value is retrieved of use promises to return the value. Both are described in the answer which this questions has been marked a duplicate of. This type of question is asked many times a day here. It's part of learning how to program in nodejs. – jfriend00 Mar 12 '17 at 04:16
  • Cool, iv just been reading through that, I'm realativly new to node and js, I was assuming that it was a promise because I kept getting errors say that it's an unhandled promise request. I think iv got a lot to learn about callbacks. – Ashton Mar 12 '17 at 04:22

0 Answers0