0

I am working on a discord bot using discord.js and I can't figure out why my function is always returning undefined. I have one function that reads a JSON File and converts it into an object and that object should then be returned so i can use it in other functions.

function getPlayer(message) {
let filename = message.author.id + '.json';
let path     = './Database/';

if(fs.existsSync(path + filename)) {

    console.log('File Found');

    fs.readFile(path + filename , 'utf-8', (err,content) => {
        if(err) {
            console.log(err)
        } else {
            let player = JSON.parse(content);
            return player;
        }
    })
} else  {
    console.log('File not found')
}}

Inside this method I can access the properties without a problem but as soon as I use the getPlayer() method to get the player object in another method I always get an error that player is not defined.

function getELO (message) {
let p = getPlayer(message);
console.log(p.name) }
  • Because `getPlayer` *does not `return` anything.* There's no `return` statement in `getPlayer`. There's a `return` statement in a nested *async callback function*, yes, but that doesn't help. – deceze Dec 22 '20 at 15:28
  • There is no `return` within `getPlayer` itself, so it implicitly returns `undefined`. You only have a `return` in the callback given to `fs.readPath`. You should use the promise API of `fs` and `await` the result (or return it directly). – VLAZ Dec 22 '20 at 15:28
  • 1
    My post on callback functions might also help to learn how to think about them: https://felix-kling.de/blog/2019/javascript-callbacks-misconceptions.html – Felix Kling Dec 22 '20 at 15:28
  • @VLAZ Could you please show me how that function would look like ? I am still pretty new to node js and havent figured out promises really – orange_whiskey Dec 22 '20 at 15:57

0 Answers0