Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js - global variable not working?

I have a problem. The log says that the variable "gData" isnt defined. But in my opinion it must be, because its global? Can you help please?

function refreshGroupData(){
        groupModel.count(function(err, count){
        gData = count;
        io.sockets.emit( 'sendGroupData', gData);
    });
        console.log ('Test: ' + gData);
    }

Thanks, Robert.

Edit:

function refreshGroupData(){
        function test(callback){
            groupModel.count(function(err, count){
                callback(count)
            });
        }
        test(function(count) {
            io.sockets.emit( 'sendGroupData', count);
            console.log('Test: ' + count);
        });
}
like image 603
nofear87 Avatar asked Sep 13 '26 13:09

nofear87


1 Answers

The problem is that you're referencing the value of the global gData variable before you set it.

Because you don't declare gData, its value cannot be evaluated until gData = count; is executed. And because that line is executed within the asynchronous groupModel.count(...) callback, the console.log(...) line is executed before that happens.

If you move the console.log call inside the callback, it will work.

function refreshGroupData() {
    groupModel.count(function(err, count) {
        gData = count;
        io.sockets.emit('sendGroupData', gData);
        console.log('Test: ' + gData);
    });
}

The proper way to do this sort of thing is like this:

function refreshGroupData(callback) {
    groupModel.count(function(err, count) {
        io.sockets.emit('sendGroupData', count);
        callback(count);
    });
}

// Calling the function and logging the result.
refreshGroupData(function(count) {
    console.log('Test: ' + count);
});
like image 70
JohnnyHK Avatar answered Sep 16 '26 07:09

JohnnyHK