Thursday, 11 May 2017

Node.JS - Check result exists before running function

I'm relatively new to Node JS. I'm attempting to query the database, and then simply emit that data to the front end using socket.io, however I've noticed that it is intermittently sending the data / not sending the data to the front end. I'm assuming that the reason behind this is because the query has not yet finished yet, and was wondering how you'd wait for the result to be accessible before continuing?

I'm using npm mysql to access the database within the socket such as below:

var mysql = require('mysql');

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

Here is my query:

    connection.query(queryString, function(err, result, fields){
        if(err) throw err;
        socket.emit('emitFunction', result);
    });



via Filthy_Rich