从不同文件中的 MySQL 查询返回值数组后的未定义值

Undefined value after returning an array of values from a MySQL query in a different file

我正在使用 Mysql 连接器,因为我需要从我的数据库中获取一些数据,但我遇到了以下问题:

我有两个文件 server.jsdbConnection.js 我在 dbConnection.js 文件中有一个 return 应该 return 一个数组并且它应该显示它在 server.js 文件中。但是,它打印出一个未定义的数组。我不明白我做错了什么,因为我还尝试在 dbConnection.js 文件中重新生成数组之前打印出数组,并且它与数据一起显示。

server.js:

const express = require('express');
const dbConnection = require('./dbConnection.js');

app.get('/', function (req, res) {
    const val1 = new Promise((resolve, reject) => {
        dbConnection
            .getData()
            .then(data => {
        resolve(data)
                })
        .catch(err => reject('error'))
    });

    Promise.all([val1])
    .then(data => {
        console.log(data) //here it prints out [undefined]
    });        
});

dbConnection.js:

const mysql = require('mysql');
const con = mysql.createConnection({
    host: "localhost",
    user: "root",
    database: "db1"
});

const getData = async ()=> {
    var array = new Array();
    const sql1 = "SELECT * FROM table1 WHERE active=1";
    con.query(sql1, function (err, result, fields) {
        if (err) throw err;
        array = [];
        for(var i=0; i<result.length; i++) {
            array.push(result[i].active);                        
        }
        console.log(array) //here it prints out the array with its values
        return array;
    });
}
module.exports.getData = getData;

编辑:也许这有助于弄清楚发生了什么。我刚刚试过了,它打印出一个空数组 []:

const mysql = require('mysql');
var array = new Array();
const con = mysql.createConnection({
    host: "localhost",
    user: "root",
    database: "db1"
});

const getData = async ()=> {
    const sql1 = "SELECT * FROM table1 WHERE active=1";
    con.query(sql1, function (err, result, fields) {
        if (err) throw err;
        //array = [];
        for(var i=0; i<result.length; i++) {
            array.push(result[i].active);

        }
        console.log(array) //here it prints out its data
        //return array;
    });
    console.log(array); //here it prints out []
}

module.exports.getData = getData;

当我在 dbConnection.js 文件中打印数组时:

当我在 server.js 文件中打印出来时:

为什么会发生这种情况以及如何解决?

提前致谢。

使用 Async/Await 和承诺。您不能将语法与回调一起使用。您必须如下更改 dbConnection.js。你必须承诺你的回调。

function myQuery(){ 
    return new Promise(function(resolve, reject){
        var array = new Array();
        const sql1 = "SELECT * FROM table1 WHERE active=1";
        con.query(sql1, function (err, result, fields) {
            if (err) throw err;
            array = [];
            for(var i=0; i<result.length; i++) {
                array.push(result[i].active);                        
            }
            console.log(array) //here it prints out the array with its values
            resolve(array);
        });
    })
}

const getData = async ()=> {
    var array= await myQuery();
    return array;       
}
module.exports.getData = getData;