我这样做:
var mysql = require('mysql');
var config = require('./../Config.js');
var connection = mysql.createConnection({
host: config.databaseConnection.host ,
user: config.databaseConnection.user,
password: config.databaseConnection.password,
database: config.databaseConnection.database
});
var executeQuery = function (querystring) {
connection.connect(function (err) {
if (err) throw err;
console.log("connected to database successfully");
connection.query(querystring,function(err,rows){
if(err) throw err;
console.log(rows);
});
});
}
module.exports = connection;
我希望我的fucntion executeQuery返回“rows”中的数据。我做了很多关于回调的搜索,但无法理解事情是如何运作的。请帮帮我。
答案 0 :(得分:0)
您可以将回调函数传递给 template: function (id) {
console.log('endpoints#template - this.templates + id:' + this.templates + id)
return this.templates + id
},
函数。像下面的东西
executeQuery
您还可以采取基于承诺的方法
var executeQuery = function (querystring, myCallbackFunction) {
connection.connect(function (err) {
if (err) throw err;
console.log("connected to database successfully");
connection.query(querystring, function (err, rows) {
if (err) throw err;
console.log(rows);
myCallbackFunction(rows);
});
});
}
const myCallbackFunction = function(rows) {
// do stuff here with rows
}
executeQuery(querystring, myCallbackFunction)
如果你需要循环,你可以做
var executeQuery = function (querystring) {
return new Promise((resolve, reject) => {
connection.connect(function (err) {
if (err) throw err;
console.log("connected to database successfully");
connection.query(querystring, function (err, rows) {
if (err) throw err;
console.log(rows);
resolve(rown);
});
});
});
}
executeQuery(querystring).then((rown) => {
// do stuff here with rows
});