0

I have a problem in passing the return value of my query. When I try to console.log the return value inside my function. It shows all the data but when I try to use return it doesn't pass the data it says undefined.

Here's my code:

server.js

var express = require('express');
var app = express();
var mysql = require('mysql');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 8000;

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'node'    
});

app.use(express.static(__dirname + '/public'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));

app.get('/', function(req, res) {
    res.sendFile(__dirname + '/index.html');
});

connection.connect();

function loadList() {

    connection.query('SELECT * FROM inventory', function(err, rows, fields){

        if(err) throw err;
        //console.log(rows); --this is ok
        return rows; //cant return the data

    });

}

io.on('connection', function(socket){

    console.log('A user is connected!!');

    var product_list = loadList(); //return no result

    socket.emit('inventory list', {list: product_list});

    socket.on('disconnect', function() {
        console.log('user disconnected!');
    });

});

http.listen(8000, function() {
    console.log('Listening on ' + port);
});

For my index.html

<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="/bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">

    try {
        var socket = io.connect('http://127.0.0.1:8000');
        //console.log(socket);
    }catch(e) {
        console.log('ERROR OCURRED: ' + e);
    }

    if(socket !== undefined) {
        socket.on('inventory list', function(data){
            console.log(data.list); //undefined return
        });
    }

</script>

Can you help me with this?

Jerielle
  • 7,144
  • 29
  • 98
  • 164

1 Answers1

1

In nodejs ,I/O operations are asynchronous ,so you need use callback style ( or use some library to manage this behavior , like promises or async ), look at this reference

function loadList(callback) {
 connection.query('SELECT * FROM inventory', function(err,rows,fields{
   //if(err) throw err; // when a error happen this will finish the main process
   if(err) return callback(err);
   return callback(null,rows)           
});
}


io.on('connection', function(socket){

    console.log('A user is connected!!');

    loadList(function(err,product_list){;
          socket.emit('inventory list', {list: product_list});
    }
});
Community
  • 1
  • 1
cshion
  • 1,173
  • 1
  • 10
  • 19
  • Thanks it works!. Now I just need to study what you said. I am just new in node. Thanks for the reference. :) – Jerielle Nov 12 '15 at 02:22