0

i'm trying to create a nodejs server but the following code is not working any advice?

var app = require('http').createServer();
var io = require('socket.io')(app);
var mysql = require('mysql');

var dblists = new Array();
pool=mysql.createPool({host : host,user : user,password: pass });   
pool.getConnection(function(err, connection){
    connection.query("use nodejs");
    connection.query('SELECT db_name,domain_name FROM tbl_dblist;',
    function (err, rows,f) {
        rows.forEach(function (entry) {
            dblists[entry["domain_name"]] = entry["db_name"];
        });
    });
});

console.log(dblists);   

Thanks in advance] The whole code:

var dblists = new Array();

app.listen(3000);
var xsocket = io.listen(app);
//console.log('Listen On Port 3000');
var pool=mysql.createPool({host : host,user : user,password: pass });   

pool.getConnection(function(err, connection){
    connection.query("use nodejs");
    connection.query('SELECT db_name,domain_name FROM tbl_dblist;',
    function (err, rows,f) {
        rows.forEach(function (entry) {
            dblists[entry["domain_name"]] = entry["db_name"];
        });
    });
});


xsocket.set('authorization', function (handshakeData, callback) {
    callback(null, true);
});


xsocket.on('connection', function (conn) {
    xsocket.emit('list',dblists);
});

1 Answer 1

1

getConnection is asynchronous, so your console.log fires before you get any values in your array.

If you put the console.log inside the method, it will work as epxected:

xsocket.on('connection', function (conn) {    
    pool.getConnection(function(err, connection){
        connection.query("use nodejs");
        connection.query('SELECT db_name,domain_name FROM tbl_dblist;',
        function (err, rows,f) {
            rows.forEach(function (entry) {
                dblists[entry["domain_name"]] = entry["db_name"];
            });
            xsocket.emit('list', dblists);
        });
    });        
});
Sign up to request clarification or add additional context in comments.

10 Comments

So there is no way for debugging?
Why? You will have your values inside the function. If you need a synchronous way, then you should probably look at async library
The problem is even if i emit the dblists i'm not getting anythin in my client
You will need to send the data to the client inside the callback. Can you post the whole code or have you tried my suggestion>
@FarshidMehrtash I've updated my answer. You will need to emit inside your callback in order to get results.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.