问题描述
我有一个用nodejs + express制作的小项目,并且我还做了一些小服务,可以在它的某些页面上共享.
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;
现在,我的问题是:当我调用module.GetServers();时,从另一个模块中,结果始终是不确定的,因为pool.getConnection是异步的(我想,我很新),所以executeQuery不会产生结果.如何强制executeQuery等待connection.query产生结果?
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?
推荐答案
在executeQuery函数中,您使用了回调函数来等待结果.通过在getResult函数中实现它们的方式相同,可以使它在查询执行后等待结果.像这样的东西.
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;
这篇关于NodeJS和mysql:等待查询结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!