R
R
rodionov122015-07-12 12:33:36
JavaScript
rodionov12, 2015-07-12 12:33:36

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

Here is a piece of my code. It is necessary to make a selection from the database, then transfer all the data to the tmp.result variable. After running this code, nothing is added. Values ​​from a DB twitch, in function it is deduced, and outside - it is empty. Tried tmp.names = {} after tmp declaration but same result. And first, an empty tmp object is output to the console, and then the already created tmp.names, although the output of tmp is below the code.
How can I correctly pass tmp.names from this function?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
SagePtr, 2015-07-12
@rodionov12

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

V
Vlad Timofeev, 2015-07-12
@PyTiMa

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 question

Ask a Question

731 491 924 answers to any question