NodeJS and mysql: wait for query result

前端 未结 1 1788
眼角桃花
眼角桃花 2021-01-03 01:19

I have a little project made with nodejs + express, and I\'ve also made a little service to be shared across some pages of it.

var mysql = require(\'mysql\')         


        
相关标签:
1条回答
  • 2021-01-03 01:52

    In your executeQuery function you have used callbacks to wait for the results. In the same way by implementing them in getResult function you can make it wait for the results after query execution. Something like this.

    var mysql = require('mysql');
    var pool = mysql.createPool({
        connectionLimit : 100,
        host     : 'host',
        user     : 'user',
        password : 'password',
        database : 'database',
        debug    : false 
     });
    
    function executeQuery(query, callback) {
      pool.getConnection(function (err, connection) {
        if (err) {
            return callback(err, null);
        }
        else if (connection) {
            connection.query(query, function (err, rows, fields) {
                connection.release();
                if (err) {
                    return callback(err, null);
                }
                return callback(null, rows);
            })
        }
        else {
            return callback(true, "No Connection");
        }
      });
    }
    
    
    function getResult(query,callback) {
      executeQuery(query, function (err, rows) {
         if (!err) {
            callback(null,rows);
         }
         else {
            callback(true,err);
         }
      });
    }
    
    function getServers() {
      getResult("select * from table",function(err,rows){
        if(!err){
            return rows;
        }else{
            console.log(err);
        }
      });   
    }
    
    exports.getList = getList;
    
    0 讨论(0)
提交回复
热议问题