Saturday 11 March 2017

Using a function that includes a promise the set the value of a variable?

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 :)



via Ashton

No comments:

Post a Comment