我有个问题。日志显示 undefined variable “gData”。但是我认为它一定是因为它是全局性的?你能帮忙吗?
function refreshGroupData(){
groupModel.count(function(err, count){
gData = count;
io.sockets.emit( 'sendGroupData', gData);
});
console.log ('Test: ' + gData);
}
谢谢,罗伯特。
编辑:
function refreshGroupData(){
function test(callback){
groupModel.count(function(err, count){
callback(count)
});
}
test(function(count) {
io.sockets.emit( 'sendGroupData', count);
console.log('Test: ' + count);
});
}
最佳答案
问题是您在设置全局gData
变量之前先引用它的值。
因为您没有声明gData
,所以在执行gData = count;
之前无法评估其值。并且由于该行是在异步groupModel.count(...)
回调中执行的,因此console.log(...)
行在此之前执行。
如果您在回调内移动console.log
调用,它将起作用。
function refreshGroupData() {
groupModel.count(function(err, count) {
gData = count;
io.sockets.emit('sendGroupData', gData);
console.log('Test: ' + gData);
});
}
做这种事情的正确方法是这样的:
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);
});
关于node.js - node.js-全局变量不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20386270/