class中的nodejs函数返回undefined

时间:2018-01-13 20:13:25

标签: node.js function class

所以,我的类中有一个应该返回一个对象的函数,但它返回undefined,我不知道它为什么会发生,这里是代码:

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;

    });

}

发生的事情是,在我调用一些mysql查询后,this._data中存储的用户数据不再存在,所以我完全失去了这一点。

1 个答案:

答案 0 :(得分:0)

connection.query是异步的,所以当你返回结构; 它将返回undefined,因为async函数 connection.query()还没有完成。尝试使用回调。定义函数时,请按以下方式定义:

const firestore = firebase.firestore()
const coll = firestore.collection('collection_name')
coll.get().then(querySnapshot => {
    // Iterate querySnapshot.docs here
})

而不是返回结构; 尝试

method.getQuests = function(callback){

然后,当您调用它并想要使用它时,请使用它:

callback(structure);