nodejs mysql await,NodeJS和mysql:等待查询结果

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值