我试图在此函数中返回变量“ results”的内容:
var qry = function(str) {
var con = connect();
var out;
var res = con.query(str, function (err, results, fields)
{
if (err) {
console.error('error: ' + err.stack);
process.exit(1);
}
return results;
});
}
然后当我调用函数时:
var res = sql.qry("select * from accounts");
console.log("result: ",res);
我在控制台中得到以下输出:
result: undefined
函数的设置方式包含一个包含文件,如下所示:
sql.js
const mysql = require('mysql');
const config = require("./config.json");
var connect = function() {
var connection = mysql.createConnection({
host : config.mysql_host,
user : config.mysql_user,
password : config.mysql_pass,
database : config.mysql_db
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
process.exit(1);
}
//console.log('connected as id ' + connection.threadId);
});
return connection;
}
var qry = function(str) {
var con = connect();
var out;
var res = con.query(str, function (err, results, fields)
{
if (err) {
console.error('error: ' + err.stack);
process.exit(1);
}
return results;
});
}
module.exports = {
connect: connect,
qry: qry
}
和
main.js
const sql = require('./sql.js');
var connection = sql.connect();
var res = sql.qry("select * from accounts");
console.log("result: ",res);