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);
});
}
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With