Search code examples
node.jssocket.ionode-mysqlasynccallback

Send db-query-result to client


Trying to send results from a node-mysql database query to the client.

Code:

io.on('connection', function(socket){
    socket.on('admin', function() {
        [...]
        locations = getUserInfo(function(e,c){...});
        [...]
    });
});

function getUserInfo(callback) {
    var json = '';
    connection.query('SELECT * from locations WHERE loc_id = 1', function(err, results, fields) {
        if(err)
           return callback(err, null);

        console.log('The query-result is: ', results[0]);

        json = JSON.stringify(results);

        console.log('JSON-result: ', json);
        callback(null, json);
    });
};

getUserInfo(function(e,c){
    console.log(c);
});

This is working as expected.

But I don't want to write it to the console but send it to the client (with socket.io). How can I do this? All my attempts ended in getting undefined as result.


Solution

  • You might be sending the locations object back, which is always undefined. Try:

    io.on('connection', function(socket){
      socket.on('admin', function() {
          getUserInfo(function(e,c){
            if(!e){
                socket.emit('locations', c);
            }
          });
      });
    });