即使在其他模块中定义后,该变量仍未定义

时间:2018-06-19 22:47:25

标签: javascript node.js module

在Player模块中,我尝试定义如下变量:

var database = require('./database');

module.exports = function(req){
  this.req = req;
  this.id = req.session.userId;
  this.name = req.session.username
  this.money = database.getMoney(this.id);
  this.positon = database.getPosition(this.id);
  this.inventory = database.getInverntory(this.id);
  this.gear = database.getGear(this.id);
  this.stats = database.getStats(this.id);
  console.log(this.money);
}

控制台将打印出undefined

这是数据库模块

module.exports.getMoney = function(userId){
    con.query(`SELECT player.money FROM player WHERE player.id_user=${userId}`,
    function(err,result,fields){
        if(err) throw err;
        console.log(result);
        return result[0].money;
    });
}

此处控制台将打印出{ money : 500 }

我也尝试过使用回调进行操作,例如:

this.money = database.getMoney(this.id,function(data){
   return data;
}
//ofcourse implemented the same callback function in database.js

仍未定义

0 个答案:

没有答案
相关问题