0

So I have this code:
http://pastebin.com/42aHz5fy (sorry,I failed at using <pre> tags in StackOverflow editor)

The console.log() inside getStats function returns an object,but in the second console.log()(outside the function,after calling it),it returns "undefined".
And this is my console:

https://i.stack.imgur.com/aU465.png

Why is it returning undefined?

var getStats = function (){
        fs.readFile('Documents/GitHub/kag-gather-irc-bot/stats.json', 'utf8', function (err,data) {
                if (err) {
                        return console.log(err);
                }
                everyStats = JSON.parse(data);
                console.log(everyStats);
                return everyStats;
        });

}
STATS = getStats();
console.log(STATS);
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
Lucas T.
  • 396
  • 4
  • 18
  • *"Why is it returning undefined?"* Because the function `getStats` doesn't return anything. There is no `return` statement in the function. – Felix Kling Feb 13 '14 at 03:48

2 Answers2

1

You can't return a value from an asynchronous method like that... all actions done on a value returned by an async call must be done within the callback.

So the solution is to use a callback which will be called once the async operation is completed and the desired value will be passed to the callback as an argument

var getStats = function (callback) {
    fs.readFile('Documents/GitHub/kag-gather-irc-bot/stats.json', 'utf8', function (err, data) {
        if (err) {
            return console.log(err);
        }
        everyStats = JSON.parse(data);
        console.log(everyStats);
        callback(everyStats);
    });

}
getStats(function (STATS) {
    console.log(STATS);
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

Because the getStats function isnt returning anything, only the function which is an argument of fs.readFile returns.

Here I have made a callback argument, so that you can do what you need with everyStats inside of a callback function.

var getStats = function (callback){
        fs.readFile('Documents/GitHub/kag-gather-irc-bot/stats.json', 'utf8', function (err,data) {
                if (err) {
                        return console.log(err);
                }
                everyStats = JSON.parse(data);
                console.log(everyStats);
                callback(everyStats);
        });

}

getStats(function(stats) {
  // do what you want with stats
});
dezman
  • 18,087
  • 10
  • 53
  • 91