在 Nodejs 中将 SELECT sql 变量数组从一个文件发送到另一个文件

Sending a SELECT sql variable array from one file to another in Nodejs

我正在尝试 module.export "rows" 从这个函数转到 anotherfile.js

"mysql.js"

const gameserverShow = function () {
    con.query(`SELECT * FROM gameservers`, (err, rows) => {
        if (err) throw err;
        return rows;
    });
 }

module.exports.gameserverShow = gameserverShow;

我试图将一个 "foreach loop" 做成一个数组并发送过来,但每次我尝试 console.log 它时,它 return "undefined"。有 different/correct 的方法吗?

"anotherfile.js"

const mysqlcon = require("./mysql.js");
      if (args[0] == 'show') {
            mysqlcon.gameserverShow();
            console.log(mysqlcon.gameserverShow.rows);
      }

你这样做的方式不对。您应该首先阅读 javascript 函数调用、回调的工作原理以及如何处理 javascript 中的异步任务。您必须使用回调或承诺异步处理它。当您在这里使用回调时,下面是基本代码。

const gameserverShow = function (callback) {
    con.query(`SELECT * FROM gameservers`, (err, rows) => {
        if (err) callback(err);
        callback(null, rows);
    });
 }

module.exports.gameserverShow = gameserverShow;

在另一个文件中

const mysqlcon = require("./mysql.js");
      if (args[0] == 'show') {
            mysqlcon.gameserverShow((error, rows) => {
               console.log(rows);
            });
      }

您可以搜索如何使用 promises 做到这一点。这里有很多问题。