nofear87
nofear87

Reputation: 869

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);
        });
}

Upvotes: 3

Views: 1080

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311865

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);
});

Upvotes: 3

Siva Atta
Siva Atta

Reputation: 91

gData variable is inside the anonymous function.. so it is local to that function.

Upvotes: 1

Related Questions