简体   繁体   中英

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

The callback only called after query done so the result should available inside the callback function. Log both err and result to see what happened

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM