Answer the question
In order to leave comments, you need to log in
How to pass a parameter to a variable inside a function?
io.sockets.on('connection', function (socket) {
socket.on('show', function (data) {
var tmp = {};
connection.query('SELECT * FROM `name` WHERE `id` = ? LIMIT 1', data, function(err, result) {
tmp.names = result[0];
console.log(tmp.names);
});
console.log(tmp);
});
});
Answer the question
In order to leave comments, you need to log in
The matter is that you confuse synchronous and asynchronous functions. Asynchronous ones are not executed immediately, because they do not return a result, but call a callback. Here in the callback you need to do something with the received value. Essentially, your code will be executed in this order:
1. var tmp = {};
2. connection.query starts working
3. console.log(tmp);
(After a while)
4. connection.query finishes and calls your unnamed function function(err, result){ ... }
5. tmp.names = result[0];
6. console.log(tmp.names);
Sir, yes, you forgot about the asynchrony of the node .. About the main feature of what you write the application on.
As they used to say: "Either the Way of the Samurai , or the Way of the Housewife "
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question