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');
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("No connection", null);
}
});
}
function getResult(query) {
return executeQuery(query, function (err, rows) {
if (!err) {
return rows;
}
else {
console.log(err);
}
});
}
function getServers()
{
var list = getResult("select * from table");
return list;
}
exports.getList = getList;
Now, my problem is: when I call module.GetServers(); from another module, result is always undefined, because pool.getConnection is async (I suppose, I'm quite new) so executeQuery yield no result.
How can I force executeQuery to wait for a result to be yielded by connection.query?
解决方案
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;