0

So, I have a function in my class that should return an object, but instead it returns undefined, which I dont know why it is happening, here's the code:

method.getQuests = function(){
    var id = this._data[0].id;
    var lvl = this._data[0].level;
    var structure = [];

    connection.query("SELECT * FROM quest WHERE player_id = ?", [id], function(errors, rowss, fieldss) {

        for(var i = 0; i < rowss.length; i++){
            var rewards = {
                "coins":rowss[i].gold,
                "xp":rowss[i].experience,
                "honor":rowss[i].honor,
                "premium":rowss[i].donut,
                "statPoints":0,
                "item":0
            };

            structure.push({
                "id": rowss[i].id,
                "character_id": id,
                "identifier": rowss[i].name,
                "type": 1,
                "stage": rowss[i].stage,
                "level": lvl,
                "status": 1,
                "duration_type": 1,
                "duration_raw": (rowss[i].duration * 60) * 4,
                "duration": rowss[i].duration * 60,
                "ts_complete": 0,
                "energy_cost": rowss[i].duration,
                "fight_difficulty": 0,
                "fight_npc_identifier": "",
                "fight_battle_id": 0,
                "used_resources": 0,
                "rewards": JSON.stringify(rewards)
            });
        }

        return structure;

    });

}

What is also happening is that after I call some mysql query my user data stored in this._data doesn't exist anymore, so Im totally lost at this point.

Farnabaz
  • 4,030
  • 1
  • 22
  • 42
Eptun
  • 13
  • 4
  • 1
    Possible duplicate of [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) – mdatsev Jan 13 '18 at 20:15

1 Answers1

0

connection.query is async, so when you return structure; it will return undefined because the async function connection.query() hasn't completed yet. Try using a callback. When you define your function, define it like this:

method.getQuests = function(callback){

And instead of return structure; try

callback(structure);

Then, when you call it and want to use it, use it like this:

method.getQuests(function(structure){
console.log(structure);
});
Tudor
  • 320
  • 1
  • 9