简体   繁体   English

Node.JS-运行功能前检查结果是否存在

[英]Node.JS - Check result exists before running function

I'm relatively new to Node JS. 我对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. 我试图查询数据库,然后使用socket.io将数据简单地发送到前端,但是我注意到它间歇性地发送数据/不发送数据到前端。 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: 我正在使用npm mysql访问套接字内的数据库,如下所示:

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 记录错误和结果以查看发生了什么

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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