从nodejs mysql连接函数返回数据

sulc1iza  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(352)

我是这样做的:

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;

我希望我的函数执行程序返回“行”中的数据。我做了很多关于回调的搜索,但不明白事情是如何运作的。请帮帮我。

hs1rzwqc

hs1rzwqc1#

您可以将回调函数传递给 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
});

如果你需要一个循环,你可以这样做

const allPromises= [];
for (let i = 0; i < loopLength; i+=1) {
  allPromises.push(executeQuery(querystring));
}
Promise.all(allPromises).then((result) => {
  // code here
}

相关问题