javascript - 变量范围 - 本地和全局[重复]

时间:2022-05-14 09:11:54

This question already has an answer here:

这个问题在这里已有答案:

i am developing a node.js applicaton where i am using the node-mysql connector. This is how i am retrieving the data:

我正在开发一个node.js应用程序,我在使用node-mysql连接器。这是我检索数据的方式:

var queryString2 = "SELECT * FROM table WHERE domain = 'xyz';"
conn.query(queryString2, function (error,results2)
    {
        if(error)
            {
                throw error;
            }
            else
        {
            abc = results2;
            console.log(abc);  //this works
        }
    }
)

console.log(abc); //this does not work

My question is how do i access the value of abc outside of the conn.query function?

我的问题是如何在conn.query函数之外访问abc的值?

1 个解决方案

#1


0  

// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();

Emit the event in your else

在你的其他地方发出这个事件

eventEmitter.emit('got-result',results2);

Handle or listen event where you want to access result2 value

处理或侦听要访问result2值的事件

eventEmitter.on('got-result', function(data){
console.log(data);
});

#1


0  

// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();

Emit the event in your else

在你的其他地方发出这个事件

eventEmitter.emit('got-result',results2);

Handle or listen event where you want to access result2 value

处理或侦听要访问result2值的事件

eventEmitter.on('got-result', function(data){
console.log(data);
});